crypton 2.2.7 → 2.3.0
raw patch · 58 files changed
+1431/−292 lines, 58 filesPVP ok
version bump matches the API change (PVP)
API changes (from Hackage documentation)
- Crypto.Cipher.Salsa: State :: ScrubbedBytes -> State
- Crypto.Cipher.Salsa: instance Control.DeepSeq.NFData Crypto.Cipher.Salsa.State
- Crypto.Cipher.Salsa: newtype State
+ Crypto.Cipher.Salsa: data State
+ Crypto.Cipher.Types: AEAD_OCB_TAG :: Int -> AEADMode
+ Crypto.PubKey.DSA: deterministicNonce :: (HashAlgorithm hashDRG, HashAlgorithm hashDigest) => hashDRG -> PrivateKey -> Digest hashDigest -> (Integer -> Maybe a) -> a
+ Crypto.PubKey.DSA: signDeterministic :: (HashAlgorithm hashDRG, HashAlgorithm hash, ByteArrayAccess msg) => hashDRG -> PrivateKey -> hash -> msg -> Signature
+ Crypto.PubKey.DSA: signDigestDeterministic :: (HashAlgorithm hashDRG, HashAlgorithm hashDigest) => hashDRG -> PrivateKey -> Digest hashDigest -> Signature
+ Crypto.Random: SystemRandomPerDraw :: SystemRandomMode
+ Crypto.Random: SystemRandomPerThread :: Int -> SystemRandomMode
+ Crypto.Random: data SystemRandomMode
+ Crypto.Random: getSystemRandomMode :: IO SystemRandomMode
+ Crypto.Random: reseedSystem :: IO ()
+ Crypto.Random: setSystemRandomMode :: SystemRandomMode -> IO ()
Files
- CHANGELOG.md +29/−6
- Crypto/Cipher/AES.hs +1/−0
- Crypto/Cipher/AES/Primitive.hs +4/−2
- Crypto/Cipher/ChaCha.hs +2/−0
- Crypto/Cipher/ChaChaPoly1305.hs +6/−5
- Crypto/Cipher/Salsa.hs +2/−7
- Crypto/Cipher/Salsa/State.hs +18/−0
- Crypto/Cipher/Twofish.hs +11/−0
- Crypto/Cipher/Twofish/Primitive.hs +1/−1
- Crypto/Cipher/Types.hs +1/−1
- Crypto/Cipher/Types/Base.hs +17/−1
- Crypto/Cipher/Types/Block.hs +5/−0
- Crypto/Cipher/Utils.hs +10/−0
- Crypto/Cipher/XSalsa.hs +1/−0
- Crypto/ConstructHash/MiyaguchiPreneel.hs +10/−7
- Crypto/ECC.hs +10/−0
- Crypto/ECC/Edwards25519.hs +1/−1
- Crypto/Error/Types.hs +1/−1
- Crypto/Hash.hs +1/−1
- Crypto/Hash/Blake2.hs +6/−2
- Crypto/Hash/IO.hs +6/−1
- Crypto/Hash/Types.hs +4/−1
- Crypto/Internal/CompatPrim.hs +1/−1
- Crypto/KDF/Argon2.hs +1/−0
- Crypto/KDF/BCryptPBKDF.hs +1/−0
- Crypto/KDF/HKDF.hs +3/−1
- Crypto/MAC/CMAC.hs +1/−1
- Crypto/MAC/HMAC.hs +57/−5
- Crypto/MAC/Poly1305.hs +2/−0
- Crypto/Number/Generate.hs +1/−1
- Crypto/Number/ModArithmetic/Pub.hs +1/−1
- Crypto/Number/Nat.hs +3/−3
- Crypto/OTP.hs +5/−0
- Crypto/PubKey/DSA.hs +51/−6
- Crypto/PubKey/ECC/ECDSA.hs +15/−22
- Crypto/PubKey/ECC/Types.hs +1/−1
- Crypto/PubKey/ECDSA.hs +32/−18
- Crypto/PubKey/EdDSA.hs +9/−0
- Crypto/PubKey/Internal.hs +145/−2
- Crypto/PubKey/MLDSA.hs +16/−7
- Crypto/PubKey/MLKEM.hs +19/−10
- Crypto/PubKey/RSA/PSS.hs +2/−2
- Crypto/PubKey/Rabin/Types.hs +1/−0
- Crypto/Random.hs +55/−15
- Crypto/Random/SysDRG.hs +69/−6
- README.md +5/−1
- cbits/crypton_aes.c +2/−2
- cbits/crypton_sysdrg.c +216/−87
- cbits/crypton_sysrandom.c +3/−0
- cbits/tests/sysdrg/run.sh +1/−1
- cbits/tests/sysdrg/sysdrg.c +122/−48
- crypton.cabal +4/−2
- tests/BlockCipher/AESSpec.hs +66/−0
- tests/ConstructHash/MiyaguchiPreneelSpec.hs +19/−4
- tests/MAC/HMACSpec.hs +20/−3
- tests/PubKey/HedgedSpec.hs +276/−0
- tests/SysDRGSpec.hs +44/−3
- tests/forkprocess/ForkProcess.hs +15/−2
CHANGELOG.md view
@@ -1,12 +1,21 @@ # CHANGELOG for crypton -## 2.2.7+## 2.3.0 -Fixes from the 2026-11 review, backported from the 2.3 series. Salsa now-refuses a 96-bit nonce (#379), and KeyedBlake2 uses a key longer than the-digest whole instead of truncating it, refusing one past the BLAKE2 maximum-(#382).+**Breaking changes.** `Salsa.State` no longer exports its constructor+(#387), Miyaguchi-Preneel output changes for every input (#389), Salsa+refuses a 96-bit nonce (#379), and the phantom parameters of IV and of the+size-indexed types are nominal (#361, #375). `AEAD_OCB` keeps its old+behaviour; use `AEAD_OCB_TAG` for RFC 7253 tags shorter than 16 bytes (#386).+ECDSA and DSA signing is hedged, so signing twice no longer gives the same+signature; `Crypto.PubKey.DSA.signDeterministic` keeps RFC 6979 (#392).+The system generator now asks the OS on every draw; `setSystemRandomMode`+restores a per-thread generator (#391). +* One-layer SysDRG and reseedSystem+ [#353](https://github.com/kazu-yamamoto/crypton/pull/353)+* Make size-dependent phantom parameters nominal+ [#361](https://github.com/kazu-yamamoto/crypton/pull/361) * fix(blake2): treat an empty MAC key as the unkeyed hash [#371](https://github.com/kazu-yamamoto/crypton/pull/371) * fix(whirlpool): count bits in 64 bits so 256 MiB updates are hashed@@ -15,7 +24,7 @@ [#373](https://github.com/kazu-yamamoto/crypton/pull/373) * fix: low-severity issues from the 2026-11 audit [#374](https://github.com/kazu-yamamoto/crypton/pull/374)-* fix: check the IV length in AES CBC/XTS+* fix: make IV's cipher parameter nominal and check the IV length in AES CBC/XTS [#375](https://github.com/kazu-yamamoto/crypton/pull/375) * fix(entropy): refuse a negative length instead of writing past an empty buffer [#376](https://github.com/kazu-yamamoto/crypton/pull/376)@@ -37,8 +46,22 @@ [#384](https://github.com/kazu-yamamoto/crypton/pull/384) * fix(cabal): leave the extension paths out without use_target_attributes [#385](https://github.com/kazu-yamamoto/crypton/pull/385)+* feat(ocb): add AEAD_OCB_TAG for RFC 7253 tags shorter than 16 bytes+ [#386](https://github.com/kazu-yamamoto/crypton/pull/386)+* Export Salsa State abstractly+ [#387](https://github.com/kazu-yamamoto/crypton/pull/387) * Require the bcrypt cost to be two digits [#388](https://github.com/kazu-yamamoto/crypton/pull/388)+* Pad Miyaguchi-Preneel input with 0x80 and zeros+ [#389](https://github.com/kazu-yamamoto/crypton/pull/389)+* Draw per draw by default, per thread on request+ [#391](https://github.com/kazu-yamamoto/crypton/pull/391)+* Hedged nonces for ECDSA and DSA+ [#392](https://github.com/kazu-yamamoto/crypton/pull/392)+* Compute hmac in one pass over one context+ [#393](https://github.com/kazu-yamamoto/crypton/pull/393)+* Build the RFC 6979 HMAC pads once per K+ [#394](https://github.com/kazu-yamamoto/crypton/pull/394) ## 2.2.6
Crypto/Cipher/AES.hs view
@@ -77,6 +77,7 @@ ; ctrCombine (CSTR aes) (IV iv) = encryptCTR aes (IV iv) \ ; aeadInit AEAD_GCM (CSTR aes) iv = gcmAeadInit aes iv \ ; aeadInit AEAD_OCB (CSTR aes) iv = AEAD (ocbMode aes) <$> ocbInit aes iv \+ ; aeadInit (AEAD_OCB_TAG t) (CSTR aes) iv = AEAD (ocbModeWithTagLength aes t) <$> ocbInitWithTagLength aes iv t \ ; aeadInit (AEAD_CCM n m l) (CSTR aes) iv = AEAD (ccmMode aes) <$> ccmInit aes iv n m l \ ; aeadInit _ _ _ = CryptoFailed CryptoError_AEADModeNotSupported \ }; \
Crypto/Cipher/AES/Primitive.hs view
@@ -92,6 +92,8 @@ ctrCombine = encryptCTR aeadInit AEAD_GCM aes iv = gcmAeadInit aes iv aeadInit AEAD_OCB aes iv = AEAD (ocbMode aes) <$> ocbInit aes iv+ aeadInit (AEAD_OCB_TAG t) aes iv =+ AEAD (ocbModeWithTagLength aes t) <$> ocbInitWithTagLength aes iv t aeadInit (AEAD_CCM n m l) aes iv = AEAD (ccmMode aes) <$> ccmInit aes iv n m l aeadInit _ _ _ = CryptoFailed CryptoError_AEADModeNotSupported instance BlockCipher128 AES where@@ -744,13 +746,13 @@ -- | initialize an OCB context with a fixed authentication tag length. ----- The tag length is expressed in bytes and must be in [0..16].+-- The tag length is expressed in bytes and must be in [1..16]. -- The IV length must be in [1..15] bytes per RFC 7253. {-# NOINLINE ocbInitWithTagLength #-} ocbInitWithTagLength :: ByteArrayAccess iv => AES -> iv -> Int -> CryptoFailable AESOCB ocbInitWithTagLength ctx iv taglen- | taglen < 0 || taglen > 16 =+ | taglen < 1 || taglen > 16 = CryptoFailed CryptoError_AuthenticationTagSizeInvalid | ivlen < 1 || ivlen > 15 = CryptoFailed CryptoError_IvSizeInvalid | otherwise = CryptoPassed $ unsafeDoIO $ do
Crypto/Cipher/ChaCha.hs view
@@ -44,6 +44,8 @@ newtype StateSimple = StateSimple ScrubbedBytes -- just ChaCha's state deriving (NFData) +-- | A ChaCha state whose 64-bit block counter can be read and set, to+-- seek in the keystream. class ChaChaState a where getCounter64 :: a -> Word64 setCounter64 :: Word64 -> a -> a
Crypto/Cipher/ChaChaPoly1305.hs view
@@ -176,10 +176,6 @@ poke p r when (r == 0) $ loop (p `plusPtr` 1) (n - 1) --- | Initialize a new ChaChaPoly1305 State------ The key length need to be 256 bits, and the nonce--- procured using either `nonce8` or `nonce12` -- | A ChaCha20Poly1305 key: thirty-two bytes, checked once here rather than -- at every use, so that 'initialize' and 'initializeX' cannot fail. newtype Key = Key ScrubbedBytes@@ -192,6 +188,11 @@ | B.length k /= 32 = CryptoFailed CryptoError_KeySizeInvalid | otherwise = CryptoPassed $ Key $ B.convert k +-- | Initialize a new ChaChaPoly1305 State from a 'key' and a nonce made+-- with 'nonce8' or 'nonce12'.+--+-- With a 96-bit nonce the block counter is 32 bits, as in RFC 8439, so one+-- message is at most 2^38 - 64 bytes; going past that is an error. initialize :: Key -> Nonce -> State initialize k (Nonce8 nonce) = initialize' maxBound k nonce -- RFC 8439: with a 96-bit nonce the counter is 32 bits and block 0 is the@@ -301,7 +302,7 @@ let Poly1305.Auth tag = finalize (headerDone st) in AuthTag tag } --- | The state behind the 'AEAD' interface, which may append the header in+-- | The state behind the t'AEAD' interface, which may append the header in -- several pieces: RFC 8439 pads the header as a whole, so the padding waits -- for the message or the tag. 'True' once it has been added. data AEADState = AEADState !Bool !State
Crypto/Cipher/Salsa.hs view
@@ -1,5 +1,4 @@ {-# LANGUAGE ForeignFunctionInterface #-}-{-# LANGUAGE GeneralizedNewtypeDeriving #-} -- | -- Module : Crypto.Cipher.Salsa@@ -11,23 +10,19 @@ initialize, combine, generate,- State (..),+ State, ) where +import Crypto.Cipher.Salsa.State import Crypto.Internal.ByteArray ( ByteArray, ByteArrayAccess,- ScrubbedBytes, ) import qualified Crypto.Internal.ByteArray as B import Crypto.Internal.Compat import Crypto.Internal.Imports import Foreign.C.Types import Foreign.Ptr---- | Salsa context-newtype State = State ScrubbedBytes- deriving (NFData) -- | Initialize a new Salsa context with the number of rounds, -- the key and the nonce associated.
+ Crypto/Cipher/Salsa/State.hs view
@@ -0,0 +1,18 @@+{-# LANGUAGE GeneralizedNewtypeDeriving #-}++-- |+-- Module : Crypto.Cipher.Salsa.State+-- License : BSD-style+-- Stability : stable+-- Portability : good+--+-- The Salsa context, shared by Salsa and XSalsa. The constructor stays in+-- this hidden module: C trusts the size and the offsets inside the bytes.+module Crypto.Cipher.Salsa.State (State (..)) where++import Crypto.Internal.ByteArray (ScrubbedBytes)+import Crypto.Internal.Imports++-- | Salsa context+newtype State = State ScrubbedBytes+ deriving (NFData)
Crypto/Cipher/Twofish.hs view
@@ -1,3 +1,11 @@+-- |+-- Module : Crypto.Cipher.Twofish+-- License : BSD-style+-- Stability : experimental+-- Portability : good+--+-- The Twofish block cipher: 16-byte blocks, with a key of 16, 24 or 32+-- bytes, one type for each. module Crypto.Cipher.Twofish ( Twofish128, Twofish192,@@ -8,6 +16,7 @@ import Crypto.Cipher.Types import Crypto.Cipher.Utils +-- | Twofish with a 128-bit (16-byte) key. newtype Twofish128 = Twofish128 Twofish instance Cipher Twofish128 where@@ -21,6 +30,7 @@ ecbEncrypt (Twofish128 key) = encrypt key ecbDecrypt (Twofish128 key) = decrypt key +-- | Twofish with a 192-bit (24-byte) key. newtype Twofish192 = Twofish192 Twofish instance Cipher Twofish192 where@@ -34,6 +44,7 @@ ecbEncrypt (Twofish192 key) = encrypt key ecbDecrypt (Twofish192 key) = decrypt key +-- | Twofish with a 256-bit (32-byte) key. newtype Twofish256 = Twofish256 Twofish instance Cipher Twofish256 where
Crypto/Cipher/Twofish/Primitive.hs view
@@ -18,7 +18,7 @@ import qualified Data.List as L import Data.Word --- Based on the Golang referance implementation+-- Based on the Golang reference implementation -- https://github.com/golang/crypto/blob/master/twofish/twofish.go -- BlockSize is the constant block size of Twofish.
Crypto/Cipher/Types.hs view
@@ -31,7 +31,7 @@ nullIV, ivAdd, - -- * Authentification Tag+ -- * Authentication Tag AuthTag (..), ) where
Crypto/Cipher/Types/Base.hs view
@@ -45,13 +45,29 @@ instance Eq AuthTag where (AuthTag a) == (AuthTag b) = B.constEq a b +-- | The CCM tag length M, in bytes (RFC 3610). data CCM_M = CCM_M4 | CCM_M6 | CCM_M8 | CCM_M10 | CCM_M12 | CCM_M14 | CCM_M16 deriving (Show, Eq)++-- | The size L of CCM's length field, in bytes (RFC 3610); the nonce is+-- @15 - L@ bytes, and a message at most @2^(8L) - 1@ bytes. data CCM_L = CCM_L2 | CCM_L3 | CCM_L4 deriving (Show, Eq) -- | AEAD Mode data AEADMode- = AEAD_OCB -- OCB3+ = -- | OCB3 (RFC 7253) with a 16-byte tag.+ --+ -- The tag length goes into the nonce, so it has to be known before+ -- anything is encrypted; this mode always uses 16 bytes. Asking+ -- 'Crypto.Cipher.Types.aeadFinalize' for fewer only cuts that tag+ -- short, which is not RFC 7253's shorter tag and does not match other+ -- implementations. Use 'AEAD_OCB_TAG' for a tag shorter than 16 bytes.+ AEAD_OCB+ | -- | OCB3 (RFC 7253) with the tag length given here, in bytes (1 to 16;+ -- 12 is RFC 7253's TAGLEN of 96 bits). The length is fixed at+ -- initialisation: the one given to 'Crypto.Cipher.Types.aeadFinalize'+ -- is ignored, and a tag of any other length fails to verify.+ AEAD_OCB_TAG Int | AEAD_CCM Int CCM_M CCM_L | AEAD_EAX | AEAD_CWC
Crypto/Cipher/Types/Block.hs view
@@ -1,6 +1,7 @@ {-# LANGUAGE ExistentialQuantification #-} {-# LANGUAGE MultiParamTypeClasses #-} {-# LANGUAGE Rank2Types #-}+{-# LANGUAGE RoleAnnotations #-} {-# LANGUAGE ViewPatterns #-} -- |@@ -62,6 +63,10 @@ -- | an IV parametrized by the cipher data IV c = forall byteArray. ByteArray byteArray => IV !byteArray++-- nominal, so that coerce cannot relabel an IV as one for another cipher,+-- whose C would read a block of its own size from it+type role IV nominal instance BlockCipher c => ByteArrayAccess (IV c) where withByteArray (IV z) f = withByteArray z f
Crypto/Cipher/Utils.hs view
@@ -1,3 +1,10 @@+-- |+-- Module : Crypto.Cipher.Utils+-- License : BSD-style+-- Stability : experimental+-- Portability : good+--+-- Helpers for writing 'Cipher' instances. module Crypto.Cipher.Utils ( validateKeySize, ) where@@ -7,6 +14,9 @@ import Data.ByteArray as BA +-- | Pass the key on if its length is one 'cipherKeySize' allows, and report+-- 'CryptoError_KeySizeInvalid' otherwise. The cipher argument only names+-- the type; it is not evaluated. validateKeySize :: (ByteArrayAccess key, Cipher cipher) => cipher -> key -> CryptoFailable key validateKeySize c k =
Crypto/Cipher/XSalsa.hs view
@@ -19,6 +19,7 @@ ) where import Crypto.Cipher.Salsa hiding (initialize)+import Crypto.Cipher.Salsa.State import Crypto.Internal.ByteArray (ByteArrayAccess) import qualified Crypto.Internal.ByteArray as B import Crypto.Internal.Compat
Crypto/ConstructHash/MiyaguchiPreneel.hs view
@@ -19,11 +19,11 @@ import Crypto.Cipher.Types import Crypto.Cipher.Types.Utils (chunk)-import Crypto.Data.Padding (Format (ZERO), pad) import Crypto.Error (throwCryptoError) import Crypto.Internal.ByteArray (ByteArray, ByteArrayAccess, Bytes) import qualified Crypto.Internal.ByteArray as B +-- | A Miyaguchi-Preneel digest, tagged with the block cipher that made it. newtype MiyaguchiPreneel a = MP Bytes deriving (ByteArrayAccess) @@ -31,6 +31,11 @@ MP b1 == MP b2 = B.constEq b1 b2 -- | Compute Miyaguchi-Preneel one way compress using the supplied block cipher.+--+-- The message is padded with 0x80 and then zeros to a whole number of blocks+-- (ISO/IEC 9797-1 method 2). Before 2.3 it was padded with zeros only, so+-- messages differing in trailing zeros, such as @\"a\"@ and @\"a\\0\"@,+-- gave the same output. compute' :: (ByteArrayAccess bin, BlockCipher cipher) => (Bytes -> cipher)@@ -40,14 +45,12 @@ -> MiyaguchiPreneel cipher -- ^ output tag compute' g =- MP . L.foldl' (step $ g) (B.replicate bsz 0) . chunks . pad (ZERO bsz) . B.convert+ MP . L.foldl' (step $ g) (B.replicate bsz 0) . chunk bsz . pad . B.convert where bsz = blockSize (g B.empty {- dummy to get block size -})- -- 'chunk' slices rather than splitting the message, which copied whatever- -- was left of it once per block- chunks msg- | B.null msg = []- | otherwise = chunk bsz (msg :: Bytes)+ pad :: Bytes -> Bytes+ pad msg = B.concat [msg, B.singleton 0x80, B.replicate (zeros msg) 0]+ zeros msg = negate (B.length msg + 1) `mod` bsz -- | Compute Miyaguchi-Preneel one way compress using the inferred block cipher. -- Only safe when KEY-SIZE equals to BLOCK-SIZE.
Crypto/ECC.hs view
@@ -74,6 +74,7 @@ , keypairGetPrivate :: !(Scalar curve) } +-- | A curve: its points, its scalars, and their encodings. class EllipticCurve curve where -- | Point on an Elliptic Curve type Point curve :: Type@@ -108,6 +109,7 @@ scalarToPoint :: proxy curve -> Scalar curve -> Point curve +-- | A curve with Diffie-Hellman. class EllipticCurve curve => EllipticCurveDH curve where -- | Generate a Diffie hellman secret value. --@@ -132,6 +134,7 @@ ecdh :: proxy curve -> Scalar curve -> Point curve -> CryptoFailable SharedSecret +-- | A curve whose points can be added, negated and multiplied. class (EllipticCurve curve, Eq (Point curve)) => EllipticCurveArith curve where -- | Add points on a curve pointAdd :: proxy curve -> Point curve -> Point curve -> Point curve@@ -145,6 +148,7 @@ -- -- | Scalar Inverse -- scalarInverse :: Scalar curve -> Scalar curve +-- | A curve with a base point and scalar arithmetic modulo its order. class (EllipticCurveArith curve, Eq (Scalar curve)) => EllipticCurveBasepointArith curve@@ -311,6 +315,8 @@ scalarAdd _ = ecScalarAdd scalarMul _ = ecScalarMul +-- | X25519 (RFC 7748), for Diffie-Hellman only. Points and scalars are+-- the 32-byte strings of RFC 7748, little-endian, not big-endian. data Curve_X25519 = Curve_X25519 deriving (Show, Data) @@ -334,6 +340,8 @@ secret = X25519.dh p s ecdh prx s p = checkNonZeroDH (ecdhRaw prx s p) +-- | X448 (RFC 7748), for Diffie-Hellman only. Points and scalars are the+-- 56-byte strings of RFC 7748, little-endian, not big-endian. data Curve_X448 = Curve_X448 deriving (Show, Data) @@ -357,6 +365,8 @@ secret = X448.dh p s ecdh prx s p = checkNonZeroDH (ecdhRaw prx s p) +-- | The twisted Edwards curve of Ed25519, for point and scalar arithmetic;+-- see "Crypto.ECC.Edwards25519". data Curve_Edwards25519 = Curve_Edwards25519 deriving (Show, Data)
Crypto/ECC/Edwards25519.hs view
@@ -9,7 +9,7 @@ -- -- Arithmetic primitives over curve edwards25519. ----- Twisted Edwards curves are a familly of elliptic curves allowing+-- Twisted Edwards curves are a family of elliptic curves allowing -- complete addition formulas without any special case and no point at -- infinity. Curve edwards25519 is based on prime 2^255 - 19 for -- efficient implementation. Equation and parameters are given in
Crypto/Error/Types.hs view
@@ -41,7 +41,7 @@ | CryptoError_PointFormatUnsupported | CryptoError_PointCoordinatesInvalid | CryptoError_ScalarMultiplicationInvalid- | -- Message authentification error+ | -- Message authentication error CryptoError_MacKeyInvalid | CryptoError_AuthenticationTagSizeInvalid | -- Prime generation error
Crypto/Hash.hs view
@@ -121,7 +121,7 @@ -- digest. The code path is independent from N but much slower than a normal -- 'hashUpdate'. The function can be called for the last bytes of a message, in -- order to exclude a variable padding, without leaking the padding length. The--- begining of the message, never impacted by the padding, should preferably go+-- beginning of the message, never impacted by the padding, should preferably go -- through 'hashUpdate' for better performance. -- -- An N that is negative or past the end takes the whole bytestring, which must
Crypto/Hash/Blake2.hs view
@@ -17,7 +17,7 @@ -- -- Implementation based from [RFC7693](https://tools.ietf.org/html/rfc7693) ----- Please consider the following when chosing a hash:+-- Please consider the following when choosing a hash: -- -- Algorithm | Target | Collision | Digest Size | -- Identifier | Arch | Security | in bytes |@@ -55,7 +55,7 @@ -- | Fast and secure alternative to SHA1 and HMAC-SHA1 ----- It is espacially known to target 32bits architectures.+-- It is especially known to target 32bits architectures. -- -- Known supported digest sizes: --@@ -157,6 +157,8 @@ foreign import ccall unsafe "crypton_blake2b_finalize" c_blake2b_finalize :: Ptr (Context a) -> Word32 -> Ptr (Digest a) -> IO () +-- | BLAKE2sp, the 8-way parallel form of BLAKE2s, with a digest of @bitlen@+-- bits: a multiple of 8, up to 256. Its output is not that of t'Blake2s'. data Blake2sp (bitlen :: Nat) = Blake2sp deriving (Show, Data) @@ -199,6 +201,8 @@ foreign import ccall unsafe "crypton_blake2sp_finalize" c_blake2sp_finalize :: Ptr (Context a) -> Word32 -> Ptr (Digest a) -> IO () +-- | BLAKE2bp, the 4-way parallel form of BLAKE2b, with a digest of @bitlen@+-- bits: a multiple of 8, up to 512. Its output is not that of t'Blake2b'. data Blake2bp (bitlen :: Nat) = Blake2bp deriving (Show, Data)
Crypto/Hash/IO.hs view
@@ -1,4 +1,5 @@ {-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE RoleAnnotations #-} {-# LANGUAGE ScopedTypeVariables #-} -- |@@ -33,6 +34,10 @@ newtype MutableContext a = MutableContext B.Bytes deriving (B.ByteArrayAccess) +-- nominal, so that coerce cannot relabel it as another hash and hand+-- the C a buffer of the wrong size+type role MutableContext nominal+ -- | Create a new mutable hash context. -- -- the algorithm used is automatically determined from the return constraint.@@ -46,7 +51,7 @@ -- | Create a new mutable hash context. ----- The algorithm is explicitely passed as parameter+-- The algorithm is explicitly passed as parameter hashMutableInitWith :: HashAlgorithm alg => alg -> IO (MutableContext alg) hashMutableInitWith _ = hashMutableInit
Crypto/Hash/Types.hs view
@@ -64,7 +64,7 @@ -- -- The interface presented here is update in place -- and lowlevel. the Hash module takes care of--- hidding the mutable interface properly.+-- hiding the mutable interface properly. class HashAlgorithm a where -- | Associated type for the block size of the hash algorithm type HashBlockSize a :: Nat@@ -141,6 +141,9 @@ -- better not hashed through this interface at all. newtype Context a = Context Bytes deriving (ByteArrayAccess, NFData)++-- nominal, as for 'Digest': the C reads a context of the algorithm's size+type role Context nominal -- | Represent a digest for a given hash algorithm. --
Crypto/Internal/CompatPrim.hs view
@@ -102,7 +102,7 @@ #endif -- | Simple wrapper to handle pre 7.8 and future, where--- most comparaison functions don't returns a boolean+-- most comparison functions don't return a boolean -- anymore. #if __GLASGOW_HASKELL__ >= 708 booleanPrim :: Int# -> Bool
Crypto/KDF/Argon2.hs view
@@ -94,6 +94,7 @@ outputMaxLength :: Int outputMaxLength = 0x7fffffff +-- | One pass of Argon2i v1.3 over 128 MiB (2^17 KiB) in four lanes. defaultOptions :: Options defaultOptions = Options
Crypto/KDF/BCryptPBKDF.hs view
@@ -40,6 +40,7 @@ import Foreign.Ptr (Ptr, castPtr) import Foreign.Storable (peekByteOff, pokeByteOff) +-- | The parameters of bcrypt_pbkdf. data Parameters = Parameters { iterCounts :: Int -- ^ The number of user-defined iterations for the algorithm
Crypto/KDF/HKDF.hs view
@@ -41,7 +41,7 @@ withByteArray (PRK hm) = B.withByteArray hm withByteArray (PRK_NoExpand sb) = B.withByteArray sb --- | Extract a Pseudo Random Key using the parameter and the underlaying hash mechanism+-- | Extract a Pseudo Random Key using the parameter and the underlying hash mechanism extract :: (HashAlgorithm a, ByteArrayAccess salt, ByteArrayAccess ikm) => salt@@ -126,6 +126,8 @@ in (if n >= hashLen then ti else B.take n ti) : loop hF ti r (i + 1) +-- | Take bytes, such as a PRK kept from an earlier 'extract', as a PRK.+-- 'Nothing' unless they are exactly the digest size of the hash. toPRK :: (HashAlgorithm a, ByteArrayAccess ba) => ba -> Maybe (PRK a) toPRK bs = case digestFromByteString bs of Nothing -> Nothing
Crypto/MAC/CMAC.hs view
@@ -8,7 +8,7 @@ -- Stability : experimental -- Portability : unknown ----- Provide the CMAC (Cipher based Message Authentification Code) base algorithm.+-- Provide the CMAC (Cipher based Message Authentication Code) base algorithm. -- <http://en.wikipedia.org/wiki/CMAC> -- <http://csrc.nist.gov/publications/nistpubs/800-38B/SP_800-38B.pdf> module Crypto.MAC.CMAC (
Crypto/MAC/HMAC.hs view
@@ -1,5 +1,6 @@ {-# LANGUAGE BangPatterns #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE ScopedTypeVariables #-} -- | -- Module : Crypto.MAC.HMAC@@ -8,7 +9,7 @@ -- Stability : experimental -- Portability : unknown ----- Provide the HMAC (Hash based Message Authentification Code) base algorithm.+-- Provide the HMAC (Hash based Message Authentication Code) base algorithm. -- <http://en.wikipedia.org/wiki/HMAC> module Crypto.MAC.HMAC ( hmac,@@ -26,11 +27,20 @@ import Crypto.Hash hiding (Context) import qualified Crypto.Hash as Hash (Context) import Crypto.Hash.IO-import Crypto.Internal.ByteArray (ByteArrayAccess, ScrubbedBytes)+import Crypto.Hash.Types (Digest (..), updateBlocks)+import Crypto.Internal.ByteArray (+ ByteArrayAccess,+ ScrubbedBytes,+ allocAndFreezePrim,+ ) import qualified Crypto.Internal.ByteArray as B import Crypto.Internal.Compat+import Data.Bits (xor) import qualified Data.ByteString.Lazy as L import Data.Memory.PtrMethods+import Data.Word (Word8)+import Foreign.Marshal.Alloc (allocaBytes)+import Foreign.Ptr (Ptr, castPtr) -- | Represent an HMAC that is a phantom type with the hash used to produce the mac. --@@ -50,7 +60,7 @@ -> message -- ^ Message to MAC -> HMAC a-hmac secret msg = finalize $ updates (initialize secret) [msg]+hmac secret msg = hmacChunks secret [msg] -- | Compute a MAC using the supplied hashing function, for a lazy input hmacLazy@@ -60,8 +70,50 @@ -> L.ByteString -- ^ Message to MAC -> HMAC a-hmacLazy secret msg = finalize $ updates (initialize secret) (L.toChunks msg)+hmacLazy secret msg = hmacChunks secret (L.toChunks msg) +-- | HMAC in one pass over one hash context and one key block, both used in+-- place and wiped afterwards. Going through 'initialize' and 'finalize'+-- builds and copies contexts, which costs several times the hashing itself+-- on a short message.+hmacChunks+ :: forall key message a+ . (ByteArrayAccess key, ByteArrayAccess message, HashAlgorithm a)+ => key -> [message] -> HMAC a+hmacChunks secret msgs = HMAC $+ Digest $+ allocAndFreezePrim dsize $ \(dig :: Ptr (Digest a)) ->+ allocaBytes csize $ \(ctx :: Ptr (Hash.Context a)) ->+ allocaBytes bsize $ \(pad :: Ptr Word8) -> do+ -- the key block: the key, or its digest when it is longer+ -- than a block, padded with zeros+ memSet pad 0 bsize+ B.withByteArray secret $ \k ->+ if klen > bsize+ then do+ hashInternalInit ctx+ updateBlocks ctx klen k+ hashInternalFinalize ctx dig+ memCopy pad (castPtr dig) (min dsize bsize)+ else memCopy pad k klen+ memXorWith pad 0x36 pad bsize+ hashInternalInit ctx+ updateBlocks ctx bsize pad+ mapM_ (\m -> B.withByteArray m $ updateBlocks ctx (B.length m)) msgs+ hashInternalFinalize ctx dig+ memXorWith pad (0x36 `xor` 0x5c) pad bsize+ hashInternalInit ctx+ updateBlocks ctx bsize pad+ updateBlocks ctx dsize (castPtr dig)+ hashInternalFinalize ctx dig+ memSet pad 0 bsize+ memSet (castPtr ctx) 0 csize+ where+ klen = B.length secret+ bsize = hashBlockSize (undefined :: a)+ dsize = hashDigestSize (undefined :: a)+ csize = hashInternalContextSize (undefined :: a)+ -- | Represent an ongoing HMAC state, that can be appended with 'update' -- and finalize to an HMAC with 'finalize' data Context hashalg = Context !(Hash.Context hashalg) !(Hash.Context hashalg)@@ -124,7 +176,7 @@ update (Context octx ictx) msg = Context octx (hashUpdate ictx msg) --- | Increamentally update a HMAC context with multiple inputs+-- | Incrementally update a HMAC context with multiple inputs updates :: (ByteArrayAccess message, HashAlgorithm a) => Context a
Crypto/MAC/Poly1305.hs view
@@ -58,6 +58,8 @@ newtype Auth = Auth Bytes deriving (ByteArrayAccess, NFData) +-- | Take sixteen bytes as a tag, to compare against a computed t'Auth'.+-- Another length is 'CryptoError_AuthenticationTagSizeInvalid'. authTag :: ByteArrayAccess b => b -> CryptoFailable Auth authTag b | B.length b /= 16 = CryptoFailed $ CryptoError_AuthenticationTagSizeInvalid
Crypto/Number/Generate.hs view
@@ -32,7 +32,7 @@ deriving (Show, Eq) -- | Generate a number for a specific size of bits,--- and optionaly set bottom and top bits+-- and optionally set bottom and top bits -- -- If the top bit policy is 'Nothing', then nothing is -- done on the highest bit (it's whatever the random generator set).
Crypto/Number/ModArithmetic/Pub.hs view
@@ -7,7 +7,7 @@ -- Portability : Good -- -- The C exponentiation for an exponent that is not a secret, and the R^2--- it keeps per modulus. Internal: 'expPub' is behind 'expFast', and+-- it keeps per modulus. Internal: 'expPub' is behind 'Crypto.Number.ModArithmetic.expFast', and -- 'expPubBytes' behind RSA's public-key operation. module Crypto.Number.ModArithmetic.Pub ( expPub,
Crypto/Number/Nat.hs view
@@ -44,14 +44,14 @@ import Crypto.Internal.Nat --- | get a runtime proof that the constraint @'IsDivisibleBy8' n@ is satified+-- | get a runtime proof that the constraint @'IsDivisibleBy8' n@ is satisfied isDivisibleBy8 :: KnownNat n => proxy n -> Maybe (IsDiv8 n n :~: 'True) isDivisibleBy8 n | mod (natVal n) 8 == 0 = Just (unsafeCoerce Refl) | otherwise = Nothing -- | get a runtime proof that the constraint @'IsAtMost' value bound@ is--- satified+-- satisfied isAtMost :: (KnownNat value, KnownNat bound) => proxy value -> proxy' bound -> Maybe ((value <=? bound) :~: 'True)@@ -60,7 +60,7 @@ | otherwise = Nothing -- | get a runtime proof that the constraint @'IsAtLeast' value bound@ is--- satified+-- satisfied isAtLeast :: (KnownNat value, KnownNat bound) => proxy value -> proxy' bound -> Maybe ((bound <=? value) :~: 'True)
Crypto/OTP.hs view
@@ -181,8 +181,13 @@ digitsPower OTP8 = 100000000 digitsPower OTP9 = 1000000000 +-- | TOTP parameters: the hash, the start time, the time step in seconds,+-- the number of digits and the clock skew allowed. Make them with+-- 'mkTOTPParams'. data TOTPParams h = TP !h !OTPTime !Word16 !OTPDigits !ClockSkew deriving (Show) +-- | How many time steps either side of the current one 'totpVerify'+-- accepts. data ClockSkew = NoSkew | OneStep | TwoSteps | ThreeSteps | FourSteps deriving (Enum, Show)
Crypto/PubKey/DSA.hs view
@@ -44,6 +44,11 @@ signDigest, signDigestWith, + -- * Deterministic nonces+ deterministicNonce,+ signDeterministic,+ signDigestDeterministic,+ -- * Verification primitive verify, verifyDigest,@@ -58,11 +63,12 @@ import Data.Data import Crypto.Hash-import Crypto.Internal.ByteArray (ByteArrayAccess)+import Crypto.Internal.ByteArray (ByteArrayAccess, ScrubbedBytes)+import qualified Crypto.Internal.ByteArray as B import Crypto.Internal.Imports import Crypto.Number.Generate import Crypto.Number.ModArithmetic (expFast, expSafe, inverse, inverseSafe)-import Crypto.PubKey.Internal (dsaTruncHashDigest)+import Crypto.PubKey.Internal (dsaTruncHashDigest, getHashAlg, rfc6979Nonce) import Crypto.Random.Types -- | DSA Public Number, usually embedded in DSA Public Key@@ -238,16 +244,55 @@ -- | Sign a digest using the private key. See 'signDigestWith' for why a -- digest rather than a @hash@ value.+--+-- The nonce is hedged: RFC 6979's, from the private key and the digest,+-- with 32 random bytes added as in its section 3.6. Repeated randomness+-- then repeats a nonce only for the same digest, which gives away nothing. signDigest :: (HashAlgorithm hash, MonadRandom m) => PrivateKey -> Digest hash -> m Signature signDigest pk digest = do- k <- generateMax q- case signDigestWith k pk digest of- Nothing -> signDigest pk digest- Just sig -> return sig+ extra <- getRandomBytes 32+ return $ nonceWith (getHashAlg digest) pk digest extra $ \k ->+ signDigestWith k pk digest++-- | Deterministic nonce generation according to RFC 6979.+--+-- The nonce is derived from the private key and the digest alone, so a+-- signature made this way needs no random number generator. The hash used+-- to seed the generator is given separately from the one the message was+-- digested with, as RFC 6979 allows. The last argument is what to do with a+-- candidate nonce; 'Nothing' draws another.+deterministicNonce+ :: (HashAlgorithm hashDRG, HashAlgorithm hashDigest)+ => hashDRG -> PrivateKey -> Digest hashDigest -> (Integer -> Maybe a) -> a+deterministicNonce alg pk digest = nonceWith alg pk digest B.empty++nonceWith+ :: (HashAlgorithm hashDRG, HashAlgorithm hashDigest)+ => hashDRG+ -> PrivateKey+ -> Digest hashDigest+ -> ScrubbedBytes+ -> (Integer -> Maybe a)+ -> a+nonceWith alg pk = rfc6979Nonce alg q (private_x pk) where (Params _ _ q) = private_params pk++-- | Sign a digest with the nonce of RFC 6979 rather than a random one.+signDigestDeterministic+ :: (HashAlgorithm hashDRG, HashAlgorithm hashDigest)+ => hashDRG -> PrivateKey -> Digest hashDigest -> Signature+signDigestDeterministic alg pk digest =+ deterministicNonce alg pk digest $ \k -> signDigestWith k pk digest++-- | Sign a message with the nonce of RFC 6979 rather than a random one.+signDeterministic+ :: (HashAlgorithm hashDRG, HashAlgorithm hash, ByteArrayAccess msg)+ => hashDRG -> PrivateKey -> hash -> msg -> Signature+signDeterministic alg pk hashAlg msg =+ signDigestDeterministic alg pk (hashWith hashAlg msg) -- | verify a bytestring using the public key. verify
Crypto/PubKey/ECC/ECDSA.hs view
@@ -32,18 +32,15 @@ import Crypto.Debug (DebugShow (..)) import Control.Monad import Data.Bits-import Data.ByteArray (ByteArrayAccess, ScrubbedBytes)+import Data.ByteArray (ByteArrayAccess)+import qualified Data.ByteArray as B import Data.Data import Crypto.Hash-import Crypto.Number.Basic-import Crypto.Number.Generate import Crypto.Number.ModArithmetic (inverse)-import Crypto.Number.Serialize import Crypto.PubKey.ECC.Prim import Crypto.PubKey.ECC.Types-import Crypto.PubKey.Internal (dsaTruncHashDigest)-import Crypto.Random.HmacDRG+import Crypto.PubKey.Internal (dsaTruncHashDigest, getHashAlg, rfc6979Nonce) import Crypto.Random.Types -- | Represent a ECDSA signature namely R and S.@@ -187,17 +184,21 @@ -- | Sign digest using the private key. --+-- The nonce is hedged: RFC 6979's, from the private key and the digest,+-- with 32 random bytes added as in its section 3.6. Repeated randomness+-- then repeats a nonce only for the same digest, which gives away nothing.+-- -- /WARNING:/ Vulnerable to timing attacks. signExtendedDigest :: (HashAlgorithm hash, MonadRandom m) => PrivateKey -> Digest hash -> m ExtendedSignature-signExtendedDigest pk digest = do- k <- generateBetween 1 (n - 1)- case signExtendedDigestWith k pk digest of- Nothing -> signExtendedDigest pk digest- Just sig -> return sig+signExtendedDigest pk@(PrivateKey curve key) digest = do+ extra <- getRandomBytes 32+ return $+ rfc6979Nonce (getHashAlg digest) n key digest extra $ \k ->+ signExtendedDigestWith k pk digest where- n = ecc_n . common_curve $ private_curve pk+ n = ecc_n $ common_curve curve -- | Sign digest using the private key. --@@ -267,15 +268,7 @@ deterministicNonce :: (HashAlgorithm hashDRG, HashAlgorithm hashDigest) => hashDRG -> PrivateKey -> Digest hashDigest -> (Integer -> Maybe a) -> a-deterministicNonce alg (PrivateKey curve key) digest go = fst $ withDRG state run+deterministicNonce alg (PrivateKey curve key) digest =+ rfc6979Nonce alg n key digest B.empty where- state = update seed $ initial alg- where- seed = i2ospOf_ bytes key <> i2ospOf_ bytes message :: ScrubbedBytes- message = dsaTruncHashDigest digest n `mod` n- run = do- k <- generatePrefix bits- if 0 < k && k < n then maybe run pure $ go k else run- bytes = (bits + 7) `unsafeShiftR` 3- bits = numBits n n = ecc_n $ common_curve curve
Crypto/PubKey/ECC/Types.hs view
@@ -57,7 +57,7 @@ rnf PointO = () -- | Define an elliptic curve in 𝔽(2^m).--- The firt parameter is the Integer representatioin of the irreducible polynomial f(x).+-- The first parameter is the Integer representation of the irreducible polynomial f(x). data CurveBinary = CurveBinary Integer CurveCommon deriving (Show, Read, Eq, Data)
Crypto/PubKey/ECDSA.hs view
@@ -63,10 +63,9 @@ import Crypto.Hash import Crypto.Internal.ByteArray (ByteArray, ByteArrayAccess) import Crypto.Internal.Imports-import Crypto.Number.Generate (generatePrefix) import Crypto.Number.ModArithmetic (inverseSafe) import qualified Crypto.PubKey.ECC.P256 as P256-import Crypto.Random.HmacDRG (initial, update)+import Crypto.PubKey.Internal (getHashAlg, rfc6979Generate) import Crypto.Random.Types import Data.Bits@@ -220,14 +219,18 @@ signWith prx k d hashAlg msg = signDigestWith prx k d (hashWith hashAlg msg) -- | Sign a digest using hash and private key.+--+-- The nonce is hedged: RFC 6979's, from the private key and the digest,+-- with 32 random bytes added as in its section 3.6. Repeated randomness+-- then repeats a nonce only for the same digest, which gives away nothing. signDigest :: (EllipticCurveECDSA curve, MonadRandom m, HashAlgorithm hash) => proxy curve -> PrivateKey curve -> Digest hash -> m (Signature curve) signDigest prx pk digest = do- k <- curveGenerateScalar prx- case signDigestWith prx k pk digest of- Nothing -> signDigest prx pk digest- Just sig -> return sig+ extra <- getRandomBytes 32+ return $+ nonceWith prx (getHashAlg digest) pk digest extra $ \k ->+ signDigestWith prx k pk digest -- | Sign a message using hash and private key. sign@@ -286,23 +289,34 @@ -> Digest hashDigest -> (Scalar curve -> Maybe a) -> a-deterministicNonce prx alg d digest go = fst $ withDRG state run+deterministicNonce prx alg d digest = nonceWith prx alg d digest B.empty++-- | 'deterministicNonce' with the additional input of RFC 6979 section 3.6+-- appended to the seed: random bytes make the hedged nonce of 'signDigest'.+nonceWith+ :: (EllipticCurveECDSA curve, HashAlgorithm hashDRG, HashAlgorithm hashDigest)+ => proxy curve+ -> hashDRG+ -> PrivateKey curve+ -> Digest hashDigest+ -> B.ScrubbedBytes+ -> (Scalar curve -> Maybe a)+ -> a+nonceWith prx alg d digest extra go =+ rfc6979Generate alg (curveOrderBits prx) seed $ \k ->+ case scalarFromInteger prx k of+ CryptoPassed s | scalarIsValid prx s -> go s+ _ -> Nothing where- state = update seed $ initial alg- -- RFC 6979 section 3.2 step d: int2octets(x) || bits2octets(h1). The- -- second is the truncated digest taken modulo the order, which is what- -- scalarAdd with zero does, its contract being to reduce there.+ -- RFC 6979 section 3.2 step d: int2octets(x) || bits2octets(h1), and+ -- then k'. The second is the truncated digest taken modulo the order,+ -- which is what scalarAdd with zero does, its contract being to reduce+ -- there. seed =- B.append (encodeScalar prx d) (encodeScalar prx z)+ B.concat [encodeScalar prx d, encodeScalar prx z, extra] :: B.ScrubbedBytes z = scalarAdd prx (tHashDigest prx digest) zeroScalar zeroScalar = throwCryptoError $ scalarFromInteger prx 0- run = do- k <- generatePrefix (curveOrderBits prx)- case scalarFromInteger prx k of- CryptoPassed s- | scalarIsValid prx s -> maybe run pure (go s)- _ -> run -- | Sign a digest with a nonce derived from the private key and the digest, -- as RFC 6979 says, rather than from a random number generator.
Crypto/PubKey/EdDSA.hs view
@@ -3,6 +3,7 @@ {-# LANGUAGE GeneralizedNewtypeDeriving #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE RankNTypes #-}+{-# LANGUAGE RoleAnnotations #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-}@@ -86,6 +87,10 @@ newtype SecretKey curve = SecretKey ScrubbedBytes deriving (Show, Eq, ByteArrayAccess, NFData) +-- nominal, so that coerce cannot relabel it as another curve and hand+-- the C a buffer of the wrong size+type role SecretKey nominal+ instance DebugShow (SecretKey curve) where debugShow = debugShowBytes "SecretKey" @@ -93,9 +98,13 @@ newtype PublicKey curve hash = PublicKey Bytes deriving (Show, Eq, ByteArrayAccess, NFData) +type role PublicKey nominal nominal+ -- | An EdDSA signature newtype Signature curve hash = Signature Bytes deriving (Show, Eq, ByteArrayAccess, NFData)++type role Signature nominal nominal -- | Elliptic curves with an implementation of EdDSA class
Crypto/PubKey/Internal.hs view
@@ -1,3 +1,5 @@+{-# LANGUAGE ScopedTypeVariables #-}+ -- | -- Module : Crypto.PubKey.Internal -- License : BSD-style@@ -9,15 +11,29 @@ (&&!), dsaTruncHash, dsaTruncHashDigest,+ getHashAlg,+ rfc6979Nonce,+ rfc6979Generate, ) where -import Data.Bits (shiftR)+import Data.Bits (shiftR, xor) import qualified Data.List as L+import Data.Word (Word8)+import Foreign.Marshal.Alloc (allocaBytes)+import Foreign.Ptr (Ptr, castPtr, plusPtr)+import Foreign.Storable (poke) import Crypto.Hash-import Crypto.Internal.ByteArray (ByteArrayAccess)+import Crypto.Hash.Types (HashAlgorithm (..), updateBlocks)+import Crypto.Internal.ByteArray (ByteArrayAccess, ScrubbedBytes)+import qualified Crypto.Internal.ByteArray as B+import Crypto.Internal.Compat (unsafeDoIO) import Crypto.Number.Basic (numBits)+import Crypto.Number.Generate (generatePrefix) import Crypto.Number.Serialize+import Crypto.Random.HmacDRG (initial, update)+import Crypto.Random.Types (withDRG)+import Data.Memory.PtrMethods (memCopy, memSet, memXorWith) -- | This is a strict version of and and' :: [Bool] -> Bool@@ -46,3 +62,130 @@ getHashAlg :: Digest hash -> hash getHashAlg _ = undefined++-- | The nonce of RFC 6979 for a group of order @n@ and private key @x@.+--+-- @extra@ is the additional input of RFC 6979 section 3.6, appended after+-- the digest: empty gives deterministic (EC)DSA, fresh random bytes give a+-- hedged nonce, which is distinct whenever either the randomness or the+-- message is. @go@ answering 'Nothing' draws the next candidate.+rfc6979Nonce+ :: (HashAlgorithm hashDRG, HashAlgorithm hashDigest)+ => hashDRG+ -> Integer+ -> Integer+ -> Digest hashDigest+ -> ScrubbedBytes+ -> (Integer -> Maybe a)+ -> a+rfc6979Nonce alg n x digest extra go =+ rfc6979Generate alg bits seed $ \k ->+ if 0 < k && k < n then go k else Nothing+ where+ -- int2octets(x) || bits2octets(h1) || k'+ seed = B.concat [i2ospOf_ bytes x, i2ospOf_ bytes h1, extra] :: ScrubbedBytes+ h1 = dsaTruncHashDigest digest n `mod` n+ bytes = (bits + 7) `div` 8+ bits = numBits n++-- | The HMAC_DRBG of RFC 6979 section 3.2, seeded (steps d and f) with+-- @seed@, giving bits2int of each @qlen@-bit candidate (step h) to @go@+-- until it answers.+--+-- The HMACs under one K share its ipad and opad contexts, which are built+-- once per K; going through 'Crypto.MAC.HMAC' builds them per HMAC.+rfc6979Generate+ :: forall hash a+ . HashAlgorithm hash+ => hash -> Int -> ScrubbedBytes -> (Integer -> Maybe a) -> a+rfc6979Generate alg qlen seed go+ | dsize > bsize = slow+ | otherwise = unsafeDoIO $+ allocaBytes dsize $ \kp ->+ allocaBytes dsize $ \vp ->+ allocaBytes dsize $ \ip ->+ allocaBytes bsize $ \pad ->+ allocaBytes (3 * csize) $ \ctxs ->+ allocaBytes 2 $ \sep ->+ run kp vp ip pad (castPtr ctxs) sep+ where+ bsize = hashBlockSize alg+ dsize = hashDigestSize alg+ csize = hashInternalContextSize alg+ tlen = (qlen + 7) `div` 8++ run+ :: Ptr Word8+ -> Ptr Word8+ -> Ptr Word8+ -> Ptr Word8+ -> Ptr (Context hash)+ -> Ptr Word8+ -> IO a+ run kp vp ip pad ictx sep = do+ let octx = ictx `plusPtr` csize :: Ptr (Context hash)+ wctx = ictx `plusPtr` (2 * csize) :: Ptr (Context hash)+ -- the ipad and opad contexts of the current K+ rekey = do+ memSet pad 0 bsize+ memCopy pad kp dsize+ memXorWith pad 0x36 pad bsize+ hashInternalInit ictx+ updateBlocks ictx bsize pad+ memXorWith pad (0x36 `xor` 0x5c) pad bsize+ hashInternalInit octx+ updateBlocks octx bsize pad+ -- HMAC_K over the parts, into out, which may be one of them+ mac parts out = do+ memCopy (castPtr wctx) (castPtr ictx) csize+ mapM_ (\(p, l) -> updateBlocks wctx l p) parts+ hashInternalFinalize wctx (castPtr ip)+ memCopy (castPtr wctx) (castPtr octx) csize+ updateBlocks wctx dsize ip+ hashInternalFinalize wctx (castPtr out)+ v = (vp, dsize)+ zero = (sep, 1)+ one = (sep `plusPtr` 1, 1)+ candidate = do+ t <- B.alloc tlen $ \tp ->+ let fill off+ | off >= tlen = return ()+ | otherwise = do+ mac [v] vp+ memCopy (tp `plusPtr` off) vp (min dsize (tlen - off))+ fill (off + dsize)+ in fill 0+ return $ os2ip (t :: ScrubbedBytes) `shiftR` (8 * tlen - qlen)+ loop = do+ k <- candidate+ case go k of+ Just r -> return r+ Nothing -> do+ mac [v, zero] kp+ rekey+ mac [v] vp+ loop+ poke sep (0 :: Word8)+ poke (sep `plusPtr` 1) (1 :: Word8)+ memSet vp 1 dsize+ memSet kp 0 dsize+ rekey+ B.withByteArray seed $ \sp -> do+ let s = (sp, B.length seed)+ mac [v, zero, s] kp+ rekey+ mac [v] vp+ mac [v, one, s] kp+ rekey+ mac [v] vp+ r <- loop+ mapM_+ (\(p, l) -> memSet p 0 l)+ [(kp, dsize), (vp, dsize), (ip, dsize), (pad, bsize), (castPtr ictx, 3 * csize)]+ return r++ -- a digest longer than the block would have to be hashed as a key+ slow = fst $ withDRG (update seed $ initial alg) slowRun+ slowRun = do+ k <- generatePrefix qlen+ maybe slowRun pure (go k)
Crypto/PubKey/MLDSA.hs view
@@ -26,6 +26,7 @@ -- and is not offered here. {-# LANGUAGE DataKinds #-} {-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE RoleAnnotations #-} {-# LANGUAGE ScopedTypeVariables #-} module Crypto.PubKey.MLDSA (@@ -123,13 +124,13 @@ -- defines, closed, carrying their sizes and the calls into the -- implementation; only the sizes are exported. class MLDSA p where- -- | Size in bytes of a 'VerificationKey' of this parameter set.+ -- | Size in bytes of a t'VerificationKey' of this parameter set. verificationKeySize :: proxy p -> Int - -- | Size in bytes of a 'SigningKey' of this parameter set.+ -- | Size in bytes of a t'SigningKey' of this parameter set. signingKeySize :: proxy p -> Int - -- | Size in bytes of a 'Signature' of this parameter set.+ -- | Size in bytes of a t'Signature' of this parameter set. signatureSize :: proxy p -> Int c_keypair :: proxy p -> Ptr Word8 -> Ptr Word8 -> Ptr Word8 -> IO CInt@@ -147,10 +148,16 @@ newtype VerificationKey p = VerificationKey Bytes deriving (Show, Eq, ByteArrayAccess, NFData) +-- nominal, so that coerce cannot relabel it as another parameter set and hand+-- the C a buffer of the wrong size+type role VerificationKey nominal+ -- | A private signing key. newtype SigningKey p = SigningKey ScrubbedBytes deriving (Eq, ByteArrayAccess, NFData) +type role SigningKey nominal+ instance Show (SigningKey p) where show _ = "SigningKey <redacted>" @@ -161,6 +168,8 @@ newtype Signature p = Signature Bytes deriving (Show, Eq, ByteArrayAccess, NFData) +type role Signature nominal+ -- | The context string a signature is bound to, at most -- 'maxContextLength' bytes. --@@ -203,7 +212,7 @@ newtype Mu = Mu Bytes deriving (Show, Eq, ByteArrayAccess, NFData) --- | Size in bytes of a 'Mu'.+-- | Size in bytes of a t'Mu'. muSize :: Int muSize = 64 @@ -223,9 +232,9 @@ => VerificationKey p -> Context -> msg -> Mu messageRepresentative vk ctx msg = muFinalize (muUpdate (muInit vk ctx) msg) --- | A 'Mu' being computed, with the message going in a piece at a time.+-- | A t'Mu' being computed, with the message going in a piece at a time. ----- The name is not 'Context': that is ML-DSA's context string, which this+-- The name is not t'Context': that is ML-DSA's context string, which this -- is built from and is not. newtype MuContext = MuContext (Hash.Context (SHAKE256 512)) @@ -341,7 +350,7 @@ -- | Generate a key pair and hand back the seed it was derived from, @xi@ -- in FIPS 204. ----- A 'SigningKey' is the expanded key and nothing else, so the seed cannot+-- A t'SigningKey' is the expanded key and nothing else, so the seed cannot -- be recovered from a pair afterwards. An application that has to write -- the key out in a form that keeps the seed -- RFC 9881 lets an ML-DSA -- private key be the seed, the expanded key, or both -- has to generate it
Crypto/PubKey/MLKEM.hs view
@@ -11,9 +11,9 @@ -- -- A key encapsulation mechanism is not a Diffie-Hellman: there is no shared -- secret to be computed from two key pairs. One side publishes an--- 'EncapsulationKey'; the other calls 'encapsulate' on it, which draws a--- fresh secret and returns it along with a 'Ciphertext' that only the holder--- of the matching 'DecapsulationKey' can turn back into that secret.+-- t'EncapsulationKey'; the other calls 'encapsulate' on it, which draws a+-- fresh secret and returns it along with a t'Ciphertext' that only the holder+-- of the matching t'DecapsulationKey' can turn back into that secret. -- -- > (ek, dk) <- generateKeyPair MLKEM768 -- the receiver -- > (ct, ss) <- encapsulate ek -- the sender@@ -28,6 +28,7 @@ -- an ML-KEM-1024 one is expected. The three are fixed by FIPS 203 and the -- class has no other instances. {-# LANGUAGE GeneralizedNewtypeDeriving #-}+{-# LANGUAGE RoleAnnotations #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE TypeOperators #-} {-# LANGUAGE ScopedTypeVariables #-}@@ -105,13 +106,13 @@ ) => MLKEM p where- -- | Size in bytes of an 'EncapsulationKey' of this parameter set.+ -- | Size in bytes of an t'EncapsulationKey' of this parameter set. encapsulationKeySize :: proxy p -> Int - -- | Size in bytes of a 'DecapsulationKey' of this parameter set.+ -- | Size in bytes of a t'DecapsulationKey' of this parameter set. decapsulationKeySize :: proxy p -> Int - -- | Size in bytes of a 'Ciphertext' of this parameter set.+ -- | Size in bytes of a t'Ciphertext' of this parameter set. ciphertextSize :: proxy p -> Int c_keypair :: proxy p -> Ptr Word8 -> Ptr Word8 -> Ptr Word8 -> IO CInt@@ -124,11 +125,17 @@ newtype MLKEMEncapsulationKey p = MLKEMEncapsulationKey Bytes deriving (Show, Eq, ByteArrayAccess, NFData) +-- nominal, so that coerce cannot relabel it as another parameter set and hand+-- the C a buffer of the wrong size+type role MLKEMEncapsulationKey nominal+ -- | A private decapsulation key, @dk@ in FIPS 203. It embeds the matching -- encapsulation key, which is why it is the larger of the two. newtype MLKEMDecapsulationKey p = MLKEMDecapsulationKey ScrubbedBytes deriving (Eq, ByteArrayAccess, NFData) +type role MLKEMDecapsulationKey nominal+ instance Show (MLKEMDecapsulationKey p) where show _ = "DecapsulationKey <redacted>" @@ -139,6 +146,8 @@ newtype MLKEMCiphertext p = MLKEMCiphertext Bytes deriving (Show, Eq, ByteArrayAccess, NFData) +type role MLKEMCiphertext nominal+ -- | Size in bytes of the seed 'keyPairFromSeed' takes, which is @d@ and @z@ -- of FIPS 203 one after the other. seedSize :: Int@@ -149,7 +158,7 @@ encapsulationCoinsSize :: Int encapsulationCoinsSize = 32 --- | Size in bytes of a 'SharedSecret'.+-- | Size in bytes of a t'SharedSecret'. sharedSecretSize :: Int sharedSecretSize = 32 @@ -224,7 +233,7 @@ -- | Generate a key pair and hand back the seed it was derived from, @d@ -- and @z@ of FIPS 203 one after the other. ----- A 'DecapsulationKey' is the expanded key and nothing else, so the seed+-- A t'DecapsulationKey' is the expanded key and nothing else, so the seed -- cannot be recovered from a pair afterwards. An application that has to -- write the key out in a form that keeps the seed has to generate it here: --@@ -324,7 +333,7 @@ -- value of these types, which is where they can be reported: -- -- * The ciphertext type check of section 7.3 is its length, and--- 'ciphertext' is the only way to build a 'Ciphertext' from bytes. There+-- 'ciphertext' is the only way to build a t'Ciphertext' from bytes. There -- is nothing else to check: a ciphertext's coefficients are compressed to -- fewer than twelve bits, so every bit pattern decodes to a value in -- range.@@ -333,7 +342,7 @@ -- 'keyPairFromSeed' satisfies it by construction. -- -- So the result is 'CryptoPassed' for every key and ciphertext this module--- can produce. It is 'CryptoFailable' rather than a bare 'SharedSecret'+-- can produce. It is 'CryptoFailable' rather than a bare t'SharedSecret' -- because the implementation checks the key again on its way through, and -- what it finds is better reported than turned into an exception. mlkemDecapsulate
Crypto/PubKey/RSA/PSS.hs view
@@ -68,7 +68,7 @@ defaultPSSParamsSHA1 :: PSSParams SHA1 ByteString ByteString defaultPSSParamsSHA1 = defaultPSSParams SHA1 --- | Sign using the PSS parameters and the salt explicitely passed as parameters.+-- | Sign using the PSS parameters and the salt explicitly passed as parameters. -- -- the function ignore SaltLength from the PSS Parameters --@@ -116,7 +116,7 @@ maskedDB = normalizeToKeySize pubBits (B.bxor db dbmask :: ByteString) em = B.concat [maskedDB, h, B.singleton (pssTrailerField params)] --- | Sign using the PSS parameters and the salt explicitely passed as parameters.+-- | Sign using the PSS parameters and the salt explicitly passed as parameters. -- -- the function ignore SaltLength from the PSS Parameters --
Crypto/PubKey/Rabin/Types.hs view
@@ -14,6 +14,7 @@ import Crypto.Number.Prime (findPrimeFromWith, generatePrime) import Crypto.Random.Types +-- | A condition a generated prime must satisfy, for 'generatePrimes'. type PrimeCondition = Integer -> Bool -- | Error possible during encryption, decryption or signing.
Crypto/Random.hs view
@@ -30,13 +30,22 @@ -- > -- > (pub, priv) <- RSA.generate 256 0x10001 ----- Where the operating system offers @getrandom(2)@ or @getentropy(3)@ the--- bytes come from a ChaCha20 generator belonging to the operating system--- thread the call runs on, seeded from the system and reseeded as it goes;--- see "Crypto.Random.SysDRG" for what that is and what it is not. Where--- it does not -- Windows, for now -- they come from the system on every--- call, as they always did. Either way the caller writes the same line.+-- Where the operating system offers @getrandom(2)@ or @getentropy(3)@,+-- every draw by default takes a fresh ChaCha20 key from the system and+-- keeps nothing afterwards ('SystemRandomPerDraw'). Where it does not --+-- Windows, for now -- the bytes come from the system on every call, as they+-- always did. Either way the caller writes the same line. --+-- 'setSystemRandomMode' with 'SystemRandomPerThread' keeps a generator per+-- operating system thread instead, seeded from the system and reseeded as+-- it goes; see "Crypto.Random.SysDRG". It is several times faster for+-- small draws. The cost is in copies of a process restored from one saved+-- image. A CRIU restore is caught on the first draw, by realtime having+-- moved against the monotonic clock, unless the interval is 0, which turns+-- the clock checks off. A restored virtual machine snapshot+-- moves neither clock, so its copies draw the same bytes until something+-- else reseeds them; use the default there, or call 'reseedSystem'.+-- -- Any Haskell thread may draw, and none has to say which generator it -- wants: --@@ -44,12 +53,11 @@ -- > -- > mapM_ (\_ -> forkIO (getRandomBytes 32 >>= use)) [1 .. 64 :: Int] ----- The generator belongs to the operating system thread that happens to be--- carrying the Haskell thread when the call is made, and is found through--- that thread's own storage rather than by anything the caller passes. A--- @forkIO@ thread moves between capabilities, so two draws from one Haskell--- thread may be answered by two generators; they are seeded independently--- of each other, so it makes no difference which one answers.+-- In 'SystemRandomPerThread', the generator belongs to the operating system+-- thread that happens to be carrying the Haskell thread when the call is+-- made. A @forkIO@ thread moves between capabilities, so two draws from one+-- Haskell thread may be answered by two generators; they are seeded+-- independently of each other, so it makes no difference which one answers. -- -- == Drawing from a generator you hold --@@ -90,7 +98,7 @@ -- -- There are two instances, one for 'IO' and one for 'MonadPseudoRandom', -- and none for the transformers, so a @ReaderT env IO@ or a @StateT s IO@--- reaches the system through 'liftIO':+-- reaches the system through 'Control.Monad.IO.Class.liftIO': -- -- > import Control.Monad.IO.Class (liftIO) -- > import Control.Monad.Trans.Reader (ReaderT)@@ -99,8 +107,7 @@ -- > newKey = liftIO (getRandomBytes 32) -- -- What that draws is what the first section describes, no more and no less:--- the 'IO' instance, the generator of the operating system thread the call--- lands on, seeded from the system and reseeded as it goes. 'liftIO' says+-- the 'IO' instance, in whichever 'SystemRandomMode' is set. @liftIO@ says -- which monad the draw happens in and nothing about where the bytes come -- from. --@@ -132,6 +139,10 @@ module Crypto.Random ( -- * Drawing from the system MonadRandom (..),+ reseedSystem,+ SystemRandomMode (..),+ setSystemRandomMode,+ getSystemRandomMode, -- * Drawing from a generator you hold Seed,@@ -160,6 +171,12 @@ import Crypto.Internal.Imports import Crypto.Random.ChaChaDRG import Crypto.Random.Entropy (EntropyError (..))+import Crypto.Random.SysDRG (+ SystemRandomMode (..),+ getSystemRandomMode,+ setSystemRandomMode,+ sysDRGReseed,+ ) import Crypto.Random.SystemDRG import Crypto.Random.Types import Data.ByteArray (ByteArray, ByteArrayAccess, ScrubbedBytes)@@ -173,6 +190,29 @@ import Data.Memory.PtrMethods (memSet) import Foreign.Ptr (Ptr, castPtr) #endif++-- | Make the generators behind 'getRandomBytes' in 'IO' reseed from the+-- system before they answer again: each thread's at its next draw, as after+-- a fork. Like OpenSSL's @RAND_poll@.+--+-- Call it after the process has been restored from a saved image -- a+-- virtual machine snapshot, a CRIU checkpoint. Every copy restored from one+-- image starts from the generator state in the image, and nothing the+-- generators can see changes when that happens, so until the next reseed of+-- their own each copy would draw the same bytes as the others. A fork needs+-- no call: the generators notice it. Draws made between the restore and+-- this call are not covered.+--+-- In 'SystemRandomPerDraw', the default, there is nothing to reseed and+-- this does nothing that matters; it is for 'SystemRandomPerThread'.+--+-- It only bumps a counter, so it is cheap and never blocks.+--+-- It reaches only those generators. One you hold, made with 'drgNew' or+-- 'drgNewSeed' before the image was saved, is a value in that image and+-- goes on as it was; make it again after this call.+reseedSystem :: IO ()+reseedSystem = sysDRGReseed -- | The material a deterministic generator is built from. Two generators -- made from one seed produce the same bytes, which is what 'drgNewSeed' is
Crypto/Random/SysDRG.hs view
@@ -9,8 +9,12 @@ -- -- The generator behind the 'Crypto.Random.MonadRandom' instance for 'IO'. ----- A ChaCha20 generator per operating system thread, seeded from a--- process-wide generator, seeded in turn from the system entropy pool.+-- By default every draw takes a fresh key from the system and keeps+-- nothing ('SystemRandomPerDraw'). What follows describes the faster+-- 'SystemRandomPerThread' mode.+--+-- A ChaCha20 generator per operating system thread, seeded straight from+-- the system entropy pool. -- The state and the reseeding live in -- @cbits\/crypton_sysdrg.c@, because a @forkIO@ thread is not an operating -- system thread -- it moves between capabilities -- so state held against@@ -31,9 +35,8 @@ -- * ChaCha20, rather than AES in counter mode. -- * SHA-512 over the system's bytes, rather than a derivation function a -- standard would have named.--- * A mebibyte per thread, and a mebibyte of issued seed for the process--- generator, as the points at which to reseed. Those numbers are a--- choice, not a result.+-- * A mebibyte per thread as the point at which to reseed. That number is+-- a choice, not a result. -- -- The pieces underneath are specified: ChaCha20 is RFC 8439, SHA-512 is -- FIPS 180-4. The way they are put together is not.@@ -54,9 +57,13 @@ -- comes after one. module Crypto.Random.SysDRG ( sysDRGBytes,+ sysDRGReseed,+ SystemRandomMode (..),+ setSystemRandomMode,+ getSystemRandomMode, ) where -import Data.Word (Word8)+import Data.Word (Word32, Word8) import Foreign.C.Types (CInt (..)) import Foreign.Ptr (Ptr) @@ -80,3 +87,59 @@ (got, out) <- B.allocRet n $ \ptr -> fromIntegral `fmap` c_sysdrg_bytes ptr (fromIntegral n) return $ if got == n then Just out else Nothing++-- Unsafe: it only bumps an atomic counter.+foreign import ccall unsafe "crypton_sysdrg_reseed"+ c_sysdrg_reseed :: IO ()++-- | Make every generator reseed before it answers again. See+-- 'Crypto.Random.reseedSystem'.+sysDRGReseed :: IO ()+sysDRGReseed = c_sysdrg_reseed++-- | Where the bytes behind 'Crypto.Random.MonadRandom' for 'IO' come from.+data SystemRandomMode+ = -- | A fresh key from the system for every draw, expanded with ChaCha20+ -- and dropped. Nothing is kept between draws, so copies of a process+ -- restored from one saved image -- a virtual machine snapshot, a CRIU+ -- checkpoint -- do not repeat each other's bytes. The default.+ SystemRandomPerDraw+ | -- | A ChaCha20 generator per operating system thread, reseeded from the+ -- system after a mebibyte, after a fork, after+ -- 'Crypto.Random.reseedSystem', and, unless the interval is 0, once+ -- this many milliseconds of running time have passed since its last+ -- seed (the default is 10) or when realtime has moved a second or+ -- more against the monotonic clock, as a CRIU restore does. With 0+ -- the clocks are not read at all. Several times faster+ -- for small draws. A restored virtual machine snapshot moves neither+ -- clock, so its copies repeat each other until one of these happens.+ SystemRandomPerThread Int+ deriving (Show, Eq)++foreign import ccall unsafe "crypton_sysdrg_set_mode"+ c_sysdrg_set_mode :: CInt -> Word32 -> IO ()++foreign import ccall unsafe "crypton_sysdrg_get_mode"+ c_sysdrg_get_mode :: IO CInt++foreign import ccall unsafe "crypton_sysdrg_get_interval"+ c_sysdrg_get_interval :: IO Word32++-- | Choose the mode for the whole process. An interval below 0 or above+-- 2^32 - 1 milliseconds is an error.+setSystemRandomMode :: SystemRandomMode -> IO ()+setSystemRandomMode SystemRandomPerDraw = do+ t <- c_sysdrg_get_interval+ c_sysdrg_set_mode 0 t+setSystemRandomMode (SystemRandomPerThread t)+ | t < 0 || toInteger t > toInteger (maxBound :: Word32) =+ error "setSystemRandomMode: reseed interval out of range"+ | otherwise = c_sysdrg_set_mode 1 (fromIntegral t)++-- | The mode in force.+getSystemRandomMode :: IO SystemRandomMode+getSystemRandomMode = do+ m <- c_sysdrg_get_mode+ if m == 1+ then SystemRandomPerThread . fromIntegral <$> c_sysdrg_get_interval+ else return SystemRandomPerDraw
README.md view
@@ -1,4 +1,8 @@-+<p align="center">+ <img src="docs/images/crypton.svg" alt="crypton" height="160">+</p>++ crypton ==========
cbits/crypton_aes.c view
@@ -256,7 +256,7 @@ #define crypton_gf_mul4(a,b,t) \ (((gf_mul4_f) (crypton_aes_branch_table[GHASH_GF_MUL4]))(a,b,t)) #else-#define GET_INIT(strenght) crypton_aes_generic_init+#define GET_INIT(strength) crypton_aes_generic_init #define GET_ECB_ENCRYPT(strength) crypton_aes_generic_encrypt_ecb #define GET_ECB_DECRYPT(strength) crypton_aes_generic_decrypt_ecb #define GET_CBC_ENCRYPT(strength) crypton_aes_generic_encrypt_cbc@@ -1181,7 +1181,7 @@ ocb_block_double(&ocb->li[2], &ocb->li[1]); ocb_block_double(&ocb->li[3], &ocb->li[2]); - /* create strech from the nonce */+ /* create stretch from the nonce */ block128_zero(&nonce); if (len > 0) { memcpy(nonce.b + (16 - len), iv, len);
cbits/crypton_sysdrg.c view
@@ -1,31 +1,44 @@ /* * The generator behind MonadRandom IO. *- * A ChaCha20 DRBG per operating system thread, seeded from a process-wide- * DRBG, which is itself seeded from the system entropy pool. This is the- * shape RFC 9180's neighbours and the other libraries have settled on, and- * it was asked for in #298.+ * A ChaCha20 DRBG per operating system thread, seeded straight from the+ * system: getrandom(2) or getentropy(3). There is no process-wide generator+ * in between (#350); glibc, Go, BoringSSL and Rust's ThreadRng do without one+ * too, and it saved one system call per thread per mebibyte. * * Per operating system thread and not per Haskell thread: a forkIO thread * moves between capabilities, so state kept against it would be shared by * threads running at the same time. That is why the state is here and * reached through pthread_getspecific rather than held in Haskell. *- * Three things force a reseed:+ * Two modes (#352). Per draw, the default, keeps no state: every draw takes+ * a fresh key from the system and expands it, so a copy of the process+ * restored from a saved image -- a VM snapshot, a CRIU checkpoint -- has+ * nothing of its own to repeat. Per thread keeps the generator described+ * above, which is faster, and reseeds it when *- * - a thread has produced CRYPTON_THREAD_RESEED bytes,- * - the process DRBG has issued CRYPTON_GLOBAL_RESEED bytes of seed,- * - the process has forked.+ * - the thread has produced CRYPTON_THREAD_RESEED bytes,+ * - the reseed interval has passed since the last seed,+ * - realtime has moved against the monotonic clock since then+ * (with an interval of 0, neither clock check is made),+ * - the process has forked,+ * - the program has called crypton_sysdrg_reseed. *- * The last one is the one that bites. A child inherits its parent's state- * and would otherwise produce the same stream; the generation counter below- * is bumped in the child by a pthread_atfork handler, and every generator- * compares against it before it answers.+ * A child inherits its parent's state, and so does every copy of a restored+ * image. A fork and crypton_sysdrg_reseed bump the generation counter+ * below, and every generator compares against it before it answers. A+ * restore keeps the monotonic clock running on from the image, so the+ * interval does not see one: CRIU puts the process in a time namespace and+ * a hypervisor rewinds the guest's counter. Under CRIU realtime jumps by+ * the time the image was away, which the clock check catches on the first+ * draw. A restored VM moves neither clock until NTP steps it, and nothing+ * here sees it: per draw, or crypton_sysdrg_reseed, is the answer there. */ #include <stdint.h> #include <string.h> #include <stdlib.h>+#include <time.h> #include "crypton_chacha.h" #include "crypton_sha512.h"@@ -47,27 +60,45 @@ #define SEED_LEN (SEED_KEY + SEED_IV) #define CRYPTON_THREAD_RESEED (1u << 20)-#define CRYPTON_GLOBAL_RESEED (1u << 20) +#define MODE_PER_DRAW 0+#define MODE_PER_THREAD 1+#define DEFAULT_INTERVAL_MS 10+/* How far realtime may move against the monotonic clock before it counts+ * as a restore: well above an NTP slew between reseeds, well below any+ * time an image spends away. */+#define OFFSET_SLACK_MS 1000+ typedef struct { crypton_chacha_context ctx; uint64_t used;- uint32_t generation;+ uint64_t seeded_at;+ int64_t offset_at;+ size_t generation; int seeded; } drg_t; -static drg_t global_drg;-static volatile uint32_t fork_generation = 0;+/* Set from any thread at any time, so atomic, and 32 bits so that no+ * platform needs libatomic for it. The interval is in milliseconds; 0+ * turns the time limit off. */+static int sysdrg_mode = MODE_PER_DRAW;+static uint32_t reseed_interval_ms = DEFAULT_INTERVAL_MS;+#define MODE() __atomic_load_n(&sysdrg_mode, __ATOMIC_RELAXED)+#define INTERVAL_MS() __atomic_load_n(&reseed_interval_ms, __ATOMIC_RELAXED) +/* Read by every draw, and bumped from any thread or a signal handler by+ * crypton_sysdrg_reseed, so it is atomic and takes no lock. size_t is 64+ * bits wherever that needs no libatomic, so it does not wrap back. */+static size_t generation_count = 0;+#define GENERATION() __atomic_load_n(&generation_count, __ATOMIC_ACQUIRE)+ #ifdef _WIN32-static CRITICAL_SECTION global_lock; /* Fls and not Tls: TlsAlloc has no destructor, so the state of every thread * that ever drew a byte would be left allocated and unscrubbed when the * thread ended. FlsAlloc takes the callback that pthread_key_create does. */ static DWORD thread_slot; static INIT_ONCE init_once = INIT_ONCE_STATIC_INIT; #else-static pthread_mutex_t global_lock = PTHREAD_MUTEX_INITIALIZER; static pthread_key_t thread_slot; static pthread_once_t init_once = PTHREAD_ONCE_INIT; #endif@@ -79,7 +110,7 @@ } /*- * Seed material for the process DRBG.+ * Seed material for a thread's DRBG. * * What the system gives goes through SHA-512 rather than into the key * directly, so that the key is a fixed size whatever the call returns, and@@ -139,12 +170,17 @@ return 1; } -static void drg_seed(drg_t *d, const uint8_t seed[SEED_LEN])+/* generation is the counter as it was before the seed was drawn: read after,+ * a reseed in between would be recorded as met by a seed from before it */+static void drg_seed(drg_t *d, const uint8_t seed[SEED_LEN], size_t generation,+ uint64_t now, int64_t offset) { crypton_chacha_init(&d->ctx, CHACHA_ROUNDS, SEED_KEY, seed, SEED_IV, seed + SEED_KEY); d->used = 0;- d->generation = fork_generation;+ d->seeded_at = now;+ d->offset_at = offset;+ d->generation = generation; d->seeded = 1; } @@ -177,41 +213,73 @@ scrub(next, sizeof next); } -static int drg_stale(const drg_t *d, uint64_t limit)+/* Milliseconds of a monotonic clock that is cheap to read; its resolution+ * of a few milliseconds is why the interval is not offered in anything+ * finer. It carries on from the image across a restore; see the top. */+static uint64_t now_ms(void) {- return !d->seeded || d->used >= limit || d->generation != fork_generation;+#if defined(_WIN32)+ return (uint64_t) GetTickCount64();+#else+ struct timespec t;+#if defined(CLOCK_MONOTONIC_COARSE)+ clock_gettime(CLOCK_MONOTONIC_COARSE, &t);+#elif defined(CLOCK_MONOTONIC_FAST)+ clock_gettime(CLOCK_MONOTONIC_FAST, &t);+#elif defined(CLOCK_MONOTONIC_RAW_APPROX)+ clock_gettime(CLOCK_MONOTONIC_RAW_APPROX, &t);+#else+ clock_gettime(CLOCK_MONOTONIC, &t);+#endif+ return (uint64_t) t.tv_sec * 1000 + (uint64_t) t.tv_nsec / 1000000;+#endif } -/* Bytes from the process DRBG, which is only ever asked for seed material. */-static int global_bytes(uint8_t *out, uint32_t len)-{- int ok = 1;+#ifdef CRYPTON_SYSDRG_TESTING+static int64_t test_realtime_shift_ms = 0;+#endif -#ifdef _WIN32- EnterCriticalSection(&global_lock);+/* Realtime minus the monotonic clock of now_ms, in milliseconds. */+static int64_t clock_offset_ms(uint64_t mono)+{+ int64_t real;+#if defined(_WIN32)+ FILETIME ft;+ ULARGE_INTEGER u;+ GetSystemTimeAsFileTime(&ft);+ u.LowPart = ft.dwLowDateTime;+ u.HighPart = ft.dwHighDateTime;+ real = (int64_t) (u.QuadPart / 10000); #else- pthread_mutex_lock(&global_lock);-#endif- if (drg_stale(&global_drg, CRYPTON_GLOBAL_RESEED)) {- uint8_t seed[SEED_LEN];- ok = seed_from_system(seed);- if (ok)- drg_seed(&global_drg, seed);- scrub(seed, sizeof seed);- }- if (ok) {- crypton_chacha_generate(out, &global_drg.ctx, len);- global_drg.used += len;- drg_rekey(&global_drg);- }-#ifdef _WIN32- LeaveCriticalSection(&global_lock);+ struct timespec t;+#if defined(CLOCK_REALTIME_COARSE)+ clock_gettime(CLOCK_REALTIME_COARSE, &t);+#elif defined(CLOCK_REALTIME_FAST)+ clock_gettime(CLOCK_REALTIME_FAST, &t); #else- pthread_mutex_unlock(&global_lock);+ clock_gettime(CLOCK_REALTIME, &t); #endif- return ok;+ real = (int64_t) t.tv_sec * 1000 + (int64_t) t.tv_nsec / 1000000;+#endif+#ifdef CRYPTON_SYSDRG_TESTING+ real += test_realtime_shift_ms;+#endif+ return real - (int64_t) mono; } +/* interval 0 turns off both clock checks, and the clocks are not read. */+static int drg_stale(const drg_t *d, uint64_t limit, uint64_t interval,+ uint64_t now, int64_t offset)+{+ int64_t moved = offset - d->offset_at;++ if (!d->seeded || d->used >= limit || d->generation != GENERATION())+ return 1;+ return interval != 0+ && (now - d->seeded_at >= interval+ || moved >= OFFSET_SLACK_MS || moved <= -OFFSET_SLACK_MS);+}+ #ifdef _WIN32 static void WINAPI thread_free(void *p) #else@@ -225,37 +293,15 @@ } #ifndef _WIN32-/* All three handlers, not just the child's. The child's first draw has to- * reseed -- the generation has changed -- and reseeding takes global_lock.- * A fork made while another thread held it would hand the child a mutex- * locked by a thread that did not come across, and the child would wait on- * it for ever. So the lock is taken before the fork and released on both- * sides of it, which is the state the child needs it in. */-static void before_fork(void)-{- pthread_mutex_lock(&global_lock);-}--static void after_fork_in_parent(void)-{- pthread_mutex_unlock(&global_lock);-}- static void after_fork_in_child(void) {- pthread_mutex_unlock(&global_lock);- fork_generation++;+ __atomic_add_fetch(&generation_count, 1, __ATOMIC_RELEASE); } #endif #ifdef CRYPTON_SYSDRG_TESTING-/* For cbits/tests/sysdrg and nothing else: hold and release the process- * generator's lock, so that a fork can be made to happen while another- * thread holds it. Nothing outside that test declares these, and the- * library is never built with this defined. */-void crypton_sysdrg_test_lock(void);-void crypton_sysdrg_test_unlock(void);-+/* For cbits/tests/sysdrg and nothing else. Nothing outside that test+ * declares these, and the library is never built with this defined. */ static drg_t *this_thread(void); /* The calling thread's ChaCha key, which is d[4..11] of the state. A test@@ -280,26 +326,47 @@ } } -void crypton_sysdrg_test_lock(void)+/* Copy the calling thread's generator and the generation out and back in,+ * as a saved image and a restore from it would: a test draws, restores, and+ * draws again, which is two copies of one image. */+static struct {+ drg_t thread;+ size_t generation;+} saved_image;++void crypton_sysdrg_test_save(void);+void crypton_sysdrg_test_restore(void);+void crypton_sysdrg_test_shift_realtime(int64_t ms);++/* Move realtime against the monotonic clock, as a CRIU restore does. */+void crypton_sysdrg_test_shift_realtime(int64_t ms) {-#ifndef _WIN32- pthread_mutex_lock(&global_lock);-#endif+ test_realtime_shift_ms += ms; } -void crypton_sysdrg_test_unlock(void)+void crypton_sysdrg_test_save(void) {-#ifndef _WIN32- pthread_mutex_unlock(&global_lock);-#endif+ drg_t *d = this_thread();++ if (d)+ saved_image.thread = *d;+ saved_image.generation = GENERATION(); }++void crypton_sysdrg_test_restore(void)+{+ drg_t *d = this_thread();++ if (d)+ *d = saved_image.thread;+ __atomic_store_n(&generation_count, saved_image.generation, __ATOMIC_RELEASE);+} #endif #ifdef _WIN32 static BOOL CALLBACK init_slot(PINIT_ONCE o, PVOID p, PVOID *c) { (void) o; (void) p; (void) c;- InitializeCriticalSection(&global_lock); thread_slot = FlsAlloc(thread_free); return TRUE; }@@ -307,7 +374,7 @@ static void init_slot(void) { pthread_key_create(&thread_slot, thread_free);- pthread_atfork(before_fork, after_fork_in_parent, after_fork_in_child);+ pthread_atfork(NULL, NULL, after_fork_in_child); } #endif @@ -343,24 +410,74 @@ return d; } +/* Per draw: a key and nonce straight from the system, expanded and dropped.+ * The system's bytes go into the key as they are; there is nothing to fix+ * the size of, and a call that comes back short is a failure. */+static int per_draw_bytes(uint8_t *out, int len)+{+ crypton_chacha_context ctx;+ uint8_t seed[SEED_LEN];++ if (crypton_sysrandom_bytes(seed, SEED_LEN) != SEED_LEN) {+ scrub(seed, sizeof seed);+ return 0;+ }+ crypton_chacha_init(&ctx, CHACHA_ROUNDS, SEED_KEY, seed,+ SEED_IV, seed + SEED_KEY);+ crypton_chacha_generate(out, &ctx, (uint32_t) len);+ scrub(seed, sizeof seed);+ scrub(&ctx, sizeof ctx);+ return len;+}++/* Choose the mode and the interval. A change bumps the generation, so a+ * thread that comes back to per-thread mode starts from a fresh seed rather+ * than from a state it left some time ago. */+void crypton_sysdrg_set_mode(int mode, uint32_t interval_ms)+{+ __atomic_store_n(&reseed_interval_ms, interval_ms, __ATOMIC_RELAXED);+ __atomic_store_n(&sysdrg_mode,+ mode == MODE_PER_THREAD ? MODE_PER_THREAD : MODE_PER_DRAW,+ __ATOMIC_RELAXED);+ __atomic_add_fetch(&generation_count, 1, __ATOMIC_RELEASE);+}++int crypton_sysdrg_get_mode(void)+{+ return MODE();+}++uint32_t crypton_sysdrg_get_interval(void)+{+ return INTERVAL_MS();+}+ /* Returns the number of bytes written, which is len unless there was no * seed to be had -- and then it is 0, so that the caller can say so rather * than hand back a buffer it cannot vouch for. */ int crypton_sysdrg_bytes(uint8_t *out, int len) { drg_t *d;+ uint64_t interval, now;+ int64_t offset; if (len < 0) return 0;+ if (MODE() == MODE_PER_DRAW)+ return per_draw_bytes(out, len); d = this_thread(); if (!d) return 0; - if (drg_stale(d, CRYPTON_THREAD_RESEED)) {+ interval = INTERVAL_MS();+ now = interval != 0 ? now_ms() : 0;+ offset = interval != 0 ? clock_offset_ms(now) : 0;+ if (drg_stale(d, CRYPTON_THREAD_RESEED, interval, now, offset)) { uint8_t seed[SEED_LEN];- int ok = global_bytes(seed, SEED_LEN);+ size_t g = GENERATION();+ int ok = seed_from_system(seed); if (ok)- drg_seed(d, seed);+ drg_seed(d, seed, g, now, offset); scrub(seed, sizeof seed); if (!ok) return 0;@@ -372,10 +489,22 @@ return len; } -/* For the tests: how many times the process has been seen to fork. */+/*+ * Make every thread's generator reseed from the system before it answers+ * again, as after a fork. For a program that knows it has been restored+ * from a saved image, which no generator can see for itself. It only bumps+ * the generation, so it takes no lock and is async-signal-safe.+ */+void crypton_sysdrg_reseed(void)+{+ __atomic_add_fetch(&generation_count, 1, __ATOMIC_RELEASE);+}++/* For the tests: how many times the generators have been told to reseed,+ * by a fork or by crypton_sysdrg_reseed. */ uint32_t crypton_sysdrg_generation(void) {- return fork_generation;+ return (uint32_t) GENERATION(); } /* For the tests: bytes this thread's generator has produced since it was
cbits/crypton_sysrandom.c view
@@ -58,6 +58,9 @@ static int sysrandom_once(uint8_t *buf, size_t n) { #if defined(__linux__)+ /* The system call, not glibc's getrandom(3): since glibc 2.41 that keeps+ * a per-thread key in user memory, which a CRIU restore copies, so+ * restored copies would repeat until the kernel next reseeds. */ return (int) syscall(SYS_getrandom, buf, n, 0); #else return (int) getrandom(buf, n, 0);
cbits/tests/sysdrg/run.sh view
@@ -1,6 +1,6 @@ #!/bin/sh # Does the generator behind MonadRandom IO survive the things that break a-# generator: a second thread, a reseed, and a fork?+# generator: a second thread, a reseed, a fork, and a restore? # # None of this can be asked from Haskell alone. A forkIO thread is not an # operating system thread, and the Haskell test suite cannot fork the way a
cbits/tests/sysdrg/sysdrg.c view
@@ -7,11 +7,16 @@ #include <sys/wait.h> void crypton_sysdrg_test_key(uint8_t out[32]);-void crypton_sysdrg_test_lock(void);-void crypton_sysdrg_test_unlock(void); int crypton_sysdrg_bytes(uint8_t *out, int len); uint32_t crypton_sysdrg_generation(void); uint64_t crypton_sysdrg_thread_used(void);+void crypton_sysdrg_reseed(void);+void crypton_sysdrg_test_save(void);+void crypton_sysdrg_test_restore(void);+void crypton_sysdrg_set_mode(int mode, uint32_t interval_ms);+int crypton_sysdrg_get_mode(void);+uint32_t crypton_sysdrg_get_interval(void);+void crypton_sysdrg_test_shift_realtime(int64_t ms); static uint64_t used_in_thread; static int fail = 0;@@ -20,27 +25,6 @@ if (!ok) fail = 1; } -/* Holds the process generator's lock for a moment, so that a fork can be- * made to happen while it is held. Releasing after a delay rather than on- * demand is deliberate: a prepare handler has to be able to take the lock,- * and a holder that waited to be told would stop the fork instead of the- * child. */-static pthread_mutex_t gate = PTHREAD_MUTEX_INITIALIZER;-static pthread_cond_t gate_cv = PTHREAD_COND_INITIALIZER;-static int holding = 0;--static void *lock_holder(void *arg) {- (void) arg;- crypton_sysdrg_test_lock();- pthread_mutex_lock(&gate);- holding = 1;- pthread_cond_broadcast(&gate_cv);- pthread_mutex_unlock(&gate);- usleep(200000);- crypton_sysdrg_test_unlock();- return NULL;-}- static void *thread_body(void *arg) { uint8_t *out = (uint8_t *) arg; check("a second OS thread gets bytes", crypton_sysdrg_bytes(out, 32) == 32);@@ -48,10 +32,38 @@ return NULL; } +/* Draws, waits while the main thread reseeds, and draws again; its used+ * count after the second draw says whether that draw was reseeded. */+static pthread_mutex_t step = PTHREAD_MUTEX_INITIALIZER;+static pthread_cond_t step_cv = PTHREAD_COND_INITIALIZER;+static int stage = 0;++static void *draw_across_reseed(void *arg) {+ uint8_t out[32];+ (void) arg;+ crypton_sysdrg_bytes(out, 32);+ crypton_sysdrg_bytes(out, 32);+ pthread_mutex_lock(&step);+ stage = 1;+ pthread_cond_broadcast(&step_cv);+ while (stage != 2) pthread_cond_wait(&step_cv, &step);+ pthread_mutex_unlock(&step);+ crypton_sysdrg_bytes(out, 32);+ used_in_thread = crypton_sysdrg_thread_used();+ return NULL;+}+ int main(void) { uint8_t a[32], b[32], big[4096]; memset(a, 0, 32); memset(b, 0, 32); + check("per draw is the default", crypton_sysdrg_get_mode() == 0);+ check("the default interval is 10 ms", crypton_sysdrg_get_interval() == 10);++ /* The per-thread generator, without the time limit so that a slow+ * machine does not reseed in the middle of a check. */+ crypton_sysdrg_set_mode(1, 0);+ check("asking for 32 bytes gives 32", crypton_sysdrg_bytes(a, 32) == 32); check("asking again gives something else", crypton_sysdrg_bytes(b, 32) == 32 && memcmp(a, b, 32) != 0);@@ -81,6 +93,7 @@ int fds[2]; if (pipe(fds) != 0) { perror("pipe"); return 2; } uint8_t parent[32], child[32];+ uint32_t g_fork = crypton_sysdrg_generation(); pid_t pid = fork(); if (pid == 0) { close(fds[0]);@@ -94,7 +107,7 @@ int status = 0; waitpid(pid, &status, 0); check("the child was able to produce bytes", r == 32 && status == 0); check("parent and child do not produce the same bytes", memcmp(parent, child, 32) != 0);- check("the fork was noticed", crypton_sysdrg_generation() == 0);+ check("the fork was noticed", crypton_sysdrg_generation() == g_fork); /* Backtracking resistance. The key that produced a draw is replaced * once the bytes are out, so a state read afterwards is not the state@@ -110,31 +123,92 @@ check("a draw replaces the key that made it", memcmp(key_before, key_after, 32) != 0); - /* A fork while another thread holds the process generator's lock. The- * child's first draw has to reseed, the generation having changed, and- * reseeding takes that lock. With no prepare and parent handlers the- * child inherits it locked and waits on it for ever -- the thread that- * would release it did not come across the fork. The alarm is what- * turns that into a failure rather than a hung test run. */- pthread_t holder;- if (pthread_create(&holder, NULL, lock_holder, NULL) != 0) {- perror("pthread_create"); return 2;- }- pthread_mutex_lock(&gate);- while (!holding) pthread_cond_wait(&gate_cv, &gate);- pthread_mutex_unlock(&gate);+ /* An explicit reseed counts as a generation, and the next draw on this+ * thread and on another starts from a fresh seed: a used count of just+ * that draw. */+ uint32_t g0 = crypton_sysdrg_generation();+ uint8_t x[32];+ crypton_sysdrg_bytes(x, 32);+ pthread_t other;+ pthread_create(&other, NULL, draw_across_reseed, NULL);+ pthread_mutex_lock(&step);+ while (stage != 1) pthread_cond_wait(&step_cv, &step);+ crypton_sysdrg_reseed();+ stage = 2;+ pthread_cond_broadcast(&step_cv);+ pthread_mutex_unlock(&step);+ pthread_join(other, NULL);+ check("a reseed is counted", crypton_sysdrg_generation() == g0 + 1);+ crypton_sysdrg_bytes(x, 32);+ check("this thread reseeds on its next draw", crypton_sysdrg_thread_used() == 32);+ check("another thread reseeds on its next draw", used_in_thread == 32); - pid_t locked_pid = fork();- if (locked_pid == 0) {- uint8_t c[32];- alarm(5);- _exit(crypton_sysdrg_bytes(c, 32) == 32 ? 0 : 1);- }- pthread_join(holder, NULL);- int locked_status = 0;- waitpid(locked_pid, &locked_status, 0);- check("a child forked while the lock was held can draw",- WIFEXITED(locked_status) && WEXITSTATUS(locked_status) == 0);+ /* A restore from a saved image. Two copies of one image draw the same+ * bytes -- that is the problem -- and a reseed after the restore is what+ * makes them differ. */+ uint8_t first[32], second[32], third[32];+ crypton_sysdrg_test_save();+ crypton_sysdrg_bytes(first, 32);+ crypton_sysdrg_test_restore();+ crypton_sysdrg_bytes(second, 32);+ check("two copies of one image draw the same bytes", memcmp(first, second, 32) == 0);+ crypton_sysdrg_test_restore();+ crypton_sysdrg_reseed();+ crypton_sysdrg_bytes(third, 32);+ check("a reseed after the restore draws other bytes", memcmp(first, third, 32) != 0);++ /* The time limit: no reseed inside the interval, one after it. */+ crypton_sysdrg_set_mode(1, 1000);+ crypton_sysdrg_bytes(x, 32);+ crypton_sysdrg_bytes(x, 32);+ check("no reseed inside the interval", crypton_sysdrg_thread_used() == 64);+ crypton_sysdrg_set_mode(1, 20);+ crypton_sysdrg_bytes(x, 32);+ usleep(60 * 1000);+ crypton_sysdrg_bytes(x, 32);+ check("a reseed once the interval has passed", crypton_sysdrg_thread_used() == 32);++ /* A CRIU restore keeps the monotonic clock going on from the image and+ * moves realtime by the time away: a copy reseeds on its first draw. */+ /* per thread, clock checks on, but an interval no test reaches */+ crypton_sysdrg_set_mode(1, 1000000);+ crypton_sysdrg_bytes(x, 32);+ crypton_sysdrg_test_save();+ crypton_sysdrg_bytes(first, 32);+ crypton_sysdrg_test_restore();+ crypton_sysdrg_bytes(second, 32);+ check("without a jump a restored copy repeats", memcmp(first, second, 32) == 0);+ crypton_sysdrg_test_restore();+ crypton_sysdrg_test_shift_realtime(5000);+ crypton_sysdrg_bytes(second, 32);+ check("a realtime jump reseeds a restored copy", memcmp(first, second, 32) != 0);+ crypton_sysdrg_test_shift_realtime(-200);+ crypton_sysdrg_bytes(x, 32);+ check("a small realtime step does not reseed", crypton_sysdrg_thread_used() == 64);++ /* An interval of 0 turns the clock checks off, the realtime one too. */+ crypton_sysdrg_set_mode(1, 0);+ crypton_sysdrg_bytes(x, 32);+ crypton_sysdrg_test_shift_realtime(5000);+ crypton_sysdrg_bytes(x, 32);+ check("interval 0 ignores a realtime jump", crypton_sysdrg_thread_used() == 64);++ /* Per draw: nothing kept, so two copies of one image differ with no+ * reseed at all, and the per-thread generator is not touched. */+ crypton_sysdrg_set_mode(0, 10);+ check("the mode can be set back to per draw", crypton_sysdrg_get_mode() == 0);+ uint64_t used = crypton_sysdrg_thread_used();+ crypton_sysdrg_test_save();+ check("per draw gives bytes", crypton_sysdrg_bytes(first, 32) == 32);+ crypton_sysdrg_test_restore();+ crypton_sysdrg_bytes(second, 32);+ check("per draw: two copies of one image differ", memcmp(first, second, 32) != 0);+ check("per draw does not use the thread's generator",+ crypton_sysdrg_thread_used() == used);+ check("per draw fills a large request", crypton_sysdrg_bytes(big, 4096) == 4096);+ pthread_create(&p1, NULL, thread_body, t1);+ pthread_join(p1, NULL);+ check("per draw: another thread differs", memcmp(t1, first, 32) != 0); return fail; }
crypton.cabal view
@@ -1,6 +1,6 @@ cabal-version: 3.0 name: crypton-version: 2.2.7+version: 2.3.0 -- crypton's own code is BSD-3-Clause. The parts of -- cbits/aes/gcm_fused_x86.c that follow picotls's fusion are MIT, and the -- vendored s2n-bignum assembly in cbits/s2n is taken under ISC, and the@@ -415,6 +415,7 @@ Crypto.Cipher.Camellia.Primitive Crypto.Cipher.CAST5.Primitive Crypto.Cipher.DES.Primitive+ Crypto.Cipher.Salsa.State Crypto.Cipher.Twofish.Primitive Crypto.Cipher.Types.AEAD Crypto.Cipher.Types.Base@@ -481,7 +482,7 @@ bytestring <0.13, primitive >=0.9 && <0.10, deepseq <1.6,- base16 >=1.0 && <1.1,+ base16 >=1.0 && <2.1, text <2.2, ram >=0.20.1 && <0.23 @@ -1059,6 +1060,7 @@ PubKey.DSASpec PubKey.ECCSpec PubKey.ECDSASpec+ PubKey.HedgedSpec PubKey.MLKEMSpec PubKey.MLKEMVectors PubKey.MLDSASpec
tests/BlockCipher/AESSpec.hs view
@@ -9,7 +9,10 @@ import Crypto.Error import Crypto.Hash (Digest, SHA256, hash) import qualified Data.ByteArray as BA+import qualified Data.ByteArray.Encoding as BAE import qualified Data.ByteString as B+import qualified Data.ByteString.Char8 as B8+import Data.Char (toLower) import Data.Maybe import Imports @@ -169,6 +172,68 @@ eitherCryptoError (() <$ aeadInit AEAD_OCB ctx (iv :: ByteString)) ok = either (const False) (const True) +-- RFC 7253 puts the tag length into the nonce, so a 12-byte OCB tag is not+-- the first 12 bytes of the 16-byte one. Expected values: RFC 7253's+-- TAGLEN=96 vector, and pycryptodome's OCB for the others.+ocbTagLengthTests :: Spec+ocbTagLengthTests =+ describe "OCB tag length" $ do+ it "RFC 7253 TAGLEN 96" $+ seal rfcKey rfcNonce rfcData rfcData 12+ `shouldBe` hex+ "1792A4E31E0755FB03E31B22116E6C2DDF9EFD6E33D536F1A0124B0A55BAE884ED93481529C76B6AD0C515F4D1CDD4FDAC4F02AA"+ forM_ others $ \(t, expected) ->+ it (show t ++ "-byte tag") $+ seal key nonce header message t `shouldBe` hex expected+ it "16 is AEAD_OCB" $+ let (tag, ct) = aeadSimpleEncrypt (ocb AEAD_OCB) header message 16+ in seal key nonce header message 16 `shouldBe` ct <> BA.convert tag+ it "opens its own" $+ let sealed = seal key nonce header message 12+ (ct, tag) = B.splitAt (B.length message) sealed+ in aeadSimpleDecrypt (ocb (AEAD_OCB_TAG 12)) header ct (AuthTag (BA.convert tag))+ `shouldBe` Just message+ it "a tag of another length does not verify" $+ let sealed = seal key nonce header message 12+ (ct, tag) = B.splitAt (B.length message) sealed+ in aeadSimpleDecrypt+ (ocb (AEAD_OCB_TAG 12))+ header+ ct+ (AuthTag (BA.convert (B.take 8 tag)))+ `shouldBe` (Nothing :: Maybe ByteString)+ it "refuses 0 and 17 bytes (a length in bits, such as 96, too)" $+ forM_ [0, 17, 96] $ \t ->+ eitherCryptoError (() <$ aeadInit (AEAD_OCB_TAG t) aes (nonce :: ByteString))+ `shouldBe` Left CryptoError_AuthenticationTagSizeInvalid+ where+ rfcKey = hex "0F0E0D0C0B0A09080706050403020100"+ rfcNonce = hex "BBAA9988776655443322110D"+ rfcData = B.pack [0 .. 39]+ key = B.pack [0 .. 15]+ nonce = B.pack [0 .. 11]+ header = "header" :: ByteString+ message = "authenticated message!" :: ByteString+ others =+ [ (8, "464F86B9EBAA4832A9F1C7CBBF5C556E344E45A3CCAA1DD7153FD0F81250")+ , (12, "1CA0A452FC72B7A30D9537C4AF253187804AA8D44D8B0211F1AAA720EBEBDC3CEF6D")+ ,+ ( 16+ , "8A0F0F603E4F9A6E7B566A7CB242CA8B9F9E9D0E5BB92444A51EB4EB4930783ED803927D2A0C"+ )+ ]+ aes = throwCryptoError (cipherInit key) :: AES.AES128+ ocb mode = throwCryptoError (aeadInit mode aes nonce)+ seal+ :: ByteString -> ByteString -> ByteString -> ByteString -> Int -> ByteString+ seal k n a p t =+ let c = throwCryptoError (cipherInit k) :: AES.AES128+ st = throwCryptoError (aeadInit (AEAD_OCB_TAG t) c n)+ (tag, ct) = aeadSimpleEncrypt st a p t+ in ct <> BA.convert tag+ hex :: String -> ByteString+ hex = either error id . BAE.convertFromBase BAE.Base16 . B8.pack . map toLower+ aeadTagLengthTests :: Spec aeadTagLengthTests = describe "AEAD tag length" $ do@@ -491,6 +556,7 @@ aeadTagLengthTests ccmMisuseTests ocbIVLengthTests+ ocbTagLengthTests ocbChunkTests gcmLongTests oneShotTests
tests/ConstructHash/MiyaguchiPreneelSpec.hs view
@@ -19,24 +19,38 @@ . B8.pack . filter (/= ' ') +-- | Values from pycryptodome's AES, chained by hand with 0x80 padding. gAES128 :: Spec gAES128 = igroup "aes128" [ runMP128 B8.empty- `shouldBe` hxs "66e94bd4 ef8a2c3b 884cfa59 ca342b2e"+ `shouldBe` hxs "bad78e72 6c1ec02b 7ebfe92b 23d9ec34" , runMP128 (hxs "01000000 00000000 00000000 00000000")- `shouldBe` hxs "46711816 e91d6ff0 59bbbf2b f58e0fd3"+ `shouldBe` hxs "ef161f2b d4ce9bcd 8a771570 a8fa51c9" , runMP128 (hxs "00000000 00000000 00000000 00000001")- `shouldBe` hxs "58e2fcce fa7e3061 367f1d57 a4e7455b"+ `shouldBe` hxs "a7206541 44a17514 cdb1a563 05420a8c" , runMP128 ( hxs $ "00000000 00000000 00000000 00000000" ++ "01" )- `shouldBe` hxs "a5ff35ae 097adf5d 646abf5e bf4c16f4"+ `shouldBe` hxs "fc2553f0 50b5fcdb 1bc589ce 811a7b43"+ , runMP128 (hxs "00000000 00000000 00000000 000000")+ `shouldBe` hxs "ff49b8df 4a97cbe0 3833e661 97620d2d"+ , runMP128 (B8.pack "a")+ `shouldBe` hxs "f4899ebc 761071fe fe85dcc2 4354711e" ] +-- | Zero padding made these pairs collide.+collisions :: Spec+collisions =+ describe "trailing zeros" $ do+ it "\"a\" and \"a\\0\" differ" $+ runMP128 (B8.pack "a") `shouldNotBe` runMP128 (B8.pack "a\0")+ it "empty and a zero block differ" $+ runMP128 B8.empty `shouldNotBe` runMP128 (B.replicate 16 0)+ igroup :: String -> [Expectation] -> Spec igroup nm = describe nm . sequence_ . zipWith (flip ($)) [1 ..] . map icase where@@ -50,3 +64,4 @@ spec :: Spec spec = do vectors+ collisions
tests/MAC/HMACSpec.hs view
@@ -1,8 +1,10 @@+{-# LANGUAGE DataKinds #-} {-# LANGUAGE OverloadedStrings #-} module MAC.HMACSpec (spec) where import Crypto.Hash (+ Blake2b_512 (..), HashAlgorithm, Keccak_224 (..), Keccak_256 (..),@@ -11,14 +13,18 @@ MD5 (..), SHA1 (..), SHA256 (..),+ SHA384 (..), SHA3_224 (..), SHA3_256 (..), SHA3_384 (..), SHA3_512 (..),+ SHA512 (..),+ SHAKE256 (..), digestFromByteString, ) import qualified Crypto.MAC.HMAC as HMAC import qualified Data.ByteString as B+import qualified Data.ByteString.Lazy as BL import Imports @@ -164,8 +170,9 @@ instance HashAlgorithm a => Arbitrary (MacIncremental a) where arbitrary = do- key <- arbitraryBSof 1 89- msg <- arbitraryBSof 1 99+ -- up to 300 bytes, past every block size, so that keys are hashed too+ key <- arbitraryBSof 0 300+ msg <- arbitraryBSof 0 99 return $ MacIncremental key msg (HMAC.hmac key msg) data MacIncrementalList a = MacIncrementalList ByteString [ByteString] (HMAC.HMAC a)@@ -173,7 +180,7 @@ instance HashAlgorithm a => Arbitrary (MacIncrementalList a) where arbitrary = do- key <- arbitraryBSof 1 89+ key <- arbitraryBSof 0 300 msgs <- choose (1, 20) >>= \n -> replicateM n (arbitraryBSof 1 99) return $ MacIncrementalList key msgs (HMAC.hmac key (B.concat msgs)) @@ -186,6 +193,11 @@ , testIncrProperties SHA3_256 , testIncrProperties SHA3_384 , testIncrProperties SHA3_512+ , testIncrProperties SHA384+ , testIncrProperties SHA512+ , testIncrProperties Blake2b_512+ , -- a digest longer than the block, which the key hashing has to cut+ testIncrProperties (SHAKE256 :: SHAKE256 2048) ] where -- testIncrProperties :: HashAlgorithm a => a -> [Property]@@ -193,6 +205,7 @@ describe (show a) $ do prop "list-one" (prop_inc0 a) prop "list-multi" (prop_inc1 a)+ prop "lazy" (prop_lazy a) prop_inc0 :: HashAlgorithm a => a -> MacIncremental a -> Bool prop_inc0 _ (MacIncremental secret msg result) =@@ -202,6 +215,10 @@ prop_inc1 _ (MacIncrementalList secret msgs result) = result `assertEq` HMAC.finalize (foldl' HMAC.update (HMAC.initialize secret) msgs)++ prop_lazy :: HashAlgorithm a => a -> MacIncrementalList a -> Bool+ prop_lazy _ (MacIncrementalList secret msgs result) =+ result `assertEq` HMAC.hmacLazy secret (BL.fromChunks msgs) spec :: Spec spec = do
+ tests/PubKey/HedgedSpec.hs view
@@ -0,0 +1,276 @@+{-# LANGUAGE DataKinds #-}+{-# LANGUAGE OverloadedStrings #-}++-- | Hedged signatures for DSA and ECDSA, and the deterministic DSA of+-- RFC 6979 that the hedged nonce is built on.+module PubKey.HedgedSpec (spec) where++import qualified Crypto.ECC as ECC+import Crypto.Error (throwCryptoError)+import Crypto.Hash+import qualified Crypto.PubKey.DSA as DSA+import qualified Crypto.PubKey.ECC.ECDSA as ECDSAOld+import qualified Crypto.PubKey.ECC.Generate as ECCG+import qualified Crypto.PubKey.ECC.Types as ECCT+import qualified Crypto.PubKey.ECDSA as ECDSA+import Crypto.Random (drgNewTest, withDRG)+import Data.Proxy (Proxy (..))++import Imports++-- | The hash a vector names.+data H = H1 | H224 | H256 | H384 | H512+ deriving (Show)++-- | RFC 6979 A.2.1 and A.2.2: a key, and for each hash and message the+-- nonce and the signature.+data Vector+ = Vector String DSA.PrivateKey [(H, ByteString, Integer, Integer, Integer)]++dsa1024 :: Vector+dsa1024 =+ Vector+ "dsa1024"+ ( DSA.PrivateKey+ ( DSA.Params+ 0x86f5ca03dcfeb225063ff830a0c769b9dd9d6153ad91d7ce27f787c43278b447e6533b86b18bed6e8a48b784a14c252c5be0dbf60b86d6385bd2f12fb763ed8873abfd3f5ba2e0a8c0a59082eac056935e529daf7c610467899c77adedfc846c881870b7b19b2b58f9be0521a17002e3bdd6b86685ee90b3d9a1b02b782b1779+ 0x07b0f92546150b62514bb771e2a0c0ce387f03bda6c56b505209ff25fd3c133d89bbcd97e904e09114d9a7defdeadfc9078ea544d2e401aeecc40bb9fbbf78fd87995a10a1c27cb7789b594ba7efb5c4326a9fe59a070e136db77175464adca417be5dce2f40d10a46a3a3943f26ab7fd9c0398ff8c76ee0a56826a8a88f1dbd+ 0x996f967f6c8e388d9e28d01e205fba957a5698b1+ )+ 0x411602cb19a6ccc34494d79d98ef1e7ed5af25f7+ )+ [+ ( H1+ , "sample"+ , 0x7bdb6b0ff756e1bb5d53583ef979082f9ad5bd5b+ , 0x2e1a0c2562b2912caaf89186fb0f42001585da55+ , 0x29efb6b0aff2d7a68eb70ca313022253b9a88df5+ )+ ,+ ( H224+ , "sample"+ , 0x562097c06782d60c3037ba7be104774344687649+ , 0x4bc3b686aea70145856814a6f1bb53346f02101e+ , 0x410697b92295d994d21edd2f4ada85566f6f94c1+ )+ ,+ ( H256+ , "sample"+ , 0x519ba0546d0c39202a7d34d7dfa5e760b318bcfb+ , 0x81f2f5850be5bc123c43f71a3033e9384611c545+ , 0x4cdd914b65eb6c66a8aaad27299bee6b035f5e89+ )+ ,+ ( H384+ , "sample"+ , 0x95897cd7bbb944aa932dbc579c1c09eb6fcfc595+ , 0x07f2108557ee0e3921bc1774f1ca9b410b4ce65a+ , 0x54df70456c86fac10fab47c1949ab83f2c6f7595+ )+ ,+ ( H512+ , "sample"+ , 0x09ece7ca27d0f5a4dd4e556c9df1d21d28104f8b+ , 0x16c3491f9b8c3fbbdd5e7a7b667057f0d8ee8e1b+ , 0x02c36a127a7b89edbb72e4ffbc71dabc7d4fc69c+ )+ ,+ ( H1+ , "test"+ , 0x5c842df4f9e344ee09f056838b42c7a17f4a6433+ , 0x42ab2052fd43e123f0607f115052a67dcd9c5c77+ , 0x183916b0230d45b9931491d4c6b0bd2fb4aaf088+ )+ ,+ ( H224+ , "test"+ , 0x4598b8efc1a53bc8aecd58d1abbb0c0c71e67297+ , 0x6868e9964e36c1689f6037f91f28d5f2c30610f2+ , 0x49cec3acdc83018c5bd2674ecaad35b8cd22940f+ )+ ,+ ( H256+ , "test"+ , 0x5a67592e8128e03a417b0484410fb72c0b630e1a+ , 0x22518c127299b0f6fdc9872b282b9e70d0790812+ , 0x6837ec18f150d55de95b5e29be7af5d01e4fe160+ )+ ,+ ( H384+ , "test"+ , 0x220156b761f6ca5e6c9f1b9cf9c24be25f98cd89+ , 0x854cf929b58d73c3cbfdc421e8d5430cd6db5e66+ , 0x91d0e0f53e22f898d158380676a871a157cda622+ )+ ,+ ( H512+ , "test"+ , 0x65d2c2eeb175e370f28c75bfcdc028d22c7dbe9c+ , 0x8ea47e475ba8ac6f2d821da3bd212d11a3deb9a0+ , 0x7c670c7ad72b6c050c109e1790008097125433e8+ )+ ]++dsa2048 :: Vector+dsa2048 =+ Vector+ "dsa2048"+ ( DSA.PrivateKey+ ( DSA.Params+ 0x9db6fb5951b66bb6fe1e140f1d2ce5502374161fd6538df1648218642f0b5c48c8f7a41aadfa187324b87674fa1822b00f1ecf8136943d7c55757264e5a1a44ffe012e9936e00c1d3e9310b01c7d179805d3058b2a9f4bb6f9716bfe6117c6b5b3cc4d9be341104ad4a80ad6c94e005f4b993e14f091eb51743bf33050c38de235567e1b34c3d6a5c0ceaa1a0f368213c3d19843d0b4b09dcb9fc72d39c8de41f1bf14d4bb4563ca28371621cad3324b6a2d392145bebfac748805236f5ca2fe92b871cd8f9c36d3292b5509ca8caa77a2adfc7bfd77dda6f71125a7456fea153e433256a2261c6a06ed3693797e7995fad5aabbcfbe3eda2741e375404ae25b+ 0x5c7ff6b06f8f143fe8288433493e4769c4d988ace5be25a0e24809670716c613d7b0cee6932f8faa7c44d2cb24523da53fbe4f6ec3595892d1aa58c4328a06c46a15662e7eaa703a1decf8bbb2d05dbe2eb956c142a338661d10461c0d135472085057f3494309ffa73c611f78b32adbb5740c361c9f35be90997db2014e2ef5aa61782f52abeb8bd6432c4dd097bc5423b285dafb60dc364e8161f4a2a35aca3a10b1c4d203cc76a470a33afdcbdd92959859abd8b56e1725252d78eac66e71ba9ae3f1dd2487199874393cd4d832186800654760e1e34c09e4d155179f9ec0dc4473f996bdce6eed1cabed8b6f116f7ad9cf505df0f998e34ab27514b0ffe7+ 0xf2c3119374ce76c9356990b465374a17f23f9ed35089bd969f61c6dde9998c1f+ )+ 0x69c7548c21d0dfea6b9a51c9ead4e27c33d3b3f180316e5bcab92c933f0e4dbc+ )+ [+ ( H1+ , "sample"+ , 0x888fa6f7738a41bdc9846466abdb8174c0338250ae50ce955ca16230f9cbd53e+ , 0x3a1b2dbd7489d6ed7e608fd036c83af396e290dbd602408e8677daabd6e7445a+ , 0xd26fcba19fa3e3058ffc02ca1596cdbb6e0d20cb37b06054f7e36ded0cdbbccf+ )+ ,+ ( H224+ , "sample"+ , 0xbc372967702082e1aa4fce892209f71ae4ad25a6dfd869334e6f153bd0c4d806+ , 0xdc9f4deada8d8ff588e98fed0ab690ffce858dc8c79376450eb6b76c24537e2c+ , 0xa65a9c3bc7babe286b195d5da68616da8d47fa0097f36dd19f517327dc848cec+ )+ ,+ ( H256+ , "sample"+ , 0x8926a27c40484216f052f4427cfd5647338b7b3939bc6573af4333569d597c52+ , 0xeace8bdbbe353c432a795d9ec556c6d021f7a03f42c36e9bc87e4ac7932cc809+ , 0x7081e175455f9247b812b74583e9e94f9ea79bd640dc962533b0680793a38d53+ )+ ,+ ( H384+ , "sample"+ , 0xc345d5ab3da0a5bcb7ec8f8fb7a7e96069e03b206371ef7d83e39068ec564920+ , 0xb2da945e91858834fd9bf616ebac151edbc4b45d27d0dd4a7f6a22739f45c00b+ , 0x19048b63d9fd6bca1d9bae3664e1bcb97f7276c306130969f63f38fa8319021b+ )+ ,+ ( H512+ , "sample"+ , 0x5a12994431785485b3f5f067221517791b85a597b7a9436995c89ed0374668fc+ , 0x2016ed092dc5fb669b8efb3d1f31a91eecb199879be0cf78f02ba062cb4c942e+ , 0xd0c76f84b5f091e141572a639a4fb8c230807eea7d55c8a154a224400aff2351+ )+ ,+ ( H1+ , "test"+ , 0x6eea486f9d41a037b2c640bc5645694ff8ff4b98d066a25f76be641ccb24ba4f+ , 0xc18270a93cfc6063f57a4dfa86024f700d980e4cf4e2cb65a504397273d98ea0+ , 0x414f22e5f31a8b6d33295c7539c1c1ba3a6160d7d68d50ac0d3a5beac2884faa+ )+ ,+ ( H224+ , "test"+ , 0x06bd4c05ed74719106223be33f2d95da6b3b541dad7bfbd7ac508213b6da6670+ , 0x272aba31572f6cc55e30bf616b7a265312018dd325be031be0cc82aa17870ea3+ , 0xe9cc286a52cce201586722d36d1e917eb96a4ebdb47932f9576ac645b3a60806+ )+ ,+ ( H256+ , "test"+ , 0x1d6ce6dda1c5d37307839cd03ab0a5cbb18e60d800937d67dfb4479aac8dead7+ , 0x8190012a1969f9957d56fccaad223186f423398d58ef5b3cefd5a4146a4476f0+ , 0x7452a53f7075d417b4b013b278d1bb8bbd21863f5e7b1cee679cf2188e1ab19e+ )+ ,+ ( H384+ , "test"+ , 0x206e61f73dbe1b2dc8be736b22b079e9dacd974db00eebbc5b64cad39cf9f91c+ , 0x239e66ddbe8f8c230a3d071d601b6ffbdfb5901f94d444c6af56f732beb954be+ , 0x6bd737513d5e72fe85d1c750e0f73921fe299b945aad1c802f15c26a43d34961+ )+ ,+ ( H512+ , "test"+ , 0xaff1651e4cd6036d57aa8b2a05ccf1a9d5a40166340ecbbdc55be10b568aa0aa+ , 0x89ec4bb1400eccff8e7d9aa515cd1de7803f2daff09693ee7fd1353e90a68307+ , 0xc9f0bdabcc0d880bb137a994cc7f3980ce91cc10faf529fc46565b15cea854e1+ )+ ]++-- | The nonce and the signature of RFC 6979, through 'DSA.deterministicNonce'+-- and 'DSA.signDeterministic', with the message's hash seeding the generator.+rfcCase :: DSA.PrivateKey -> (H, ByteString, Integer, Integer, Integer) -> Spec+rfcCase pk (h, m, k, r, s) = it (show h ++ " " ++ show m) $ case h of+ H1 -> check SHA1+ H224 -> check SHA224+ H256 -> check SHA256+ H384 -> check SHA384+ H512 -> check SHA512+ where+ check :: HashAlgorithm a => a -> Expectation+ check alg = do+ DSA.deterministicNonce alg pk (hashWith alg m) Just `shouldBe` k+ DSA.signDeterministic alg pk alg m `shouldBe` DSA.Signature r s++-- | What a hedged signer must do: give the same signature for the same+-- message and the same randomness, a different nonce -- so a different r --+-- for another message under that same randomness, a different signature for+-- other randomness, and signatures that verify.+hedged+ :: (Eq sig, Show sig, Eq r, Show r)+ => (ByteString -> (Word64, Word64, Word64, Word64, Word64) -> sig)+ -> (sig -> r)+ -> (ByteString -> sig -> Bool)+ -> Spec+hedged signAt rOf ok = do+ let s1 = signAt "message one" seedA+ s1' = signAt "message one" seedA+ s2 = signAt "message two" seedA+ s3 = signAt "message one" seedB+ it "repeats only for the same message and randomness" $ s1 `shouldBe` s1'+ it "changes the nonce with the message under repeated randomness" $+ rOf s1 `shouldNotBe` rOf s2+ it "changes with the randomness" $ s1 `shouldNotBe` s3+ it "verifies" $+ (ok "message one" s1, ok "message two" s2) `shouldBe` (True, True)+ where+ seedA = (1, 2, 3, 4, 5)+ seedB = (6, 7, 8, 9, 10)++spec :: Spec+spec = do+ describe "RFC 6979 deterministic DSA" $+ mapM_+ (\(Vector name pk cases) -> describe name $ mapM_ (rfcCase pk) cases)+ [dsa1024, dsa2048]+ describe "a generator hash whose digest is longer than its block" $+ it "still gives a nonce that signs" $ do+ let Vector _ pk _ = dsa2048+ pub = DSA.PublicKey (DSA.private_params pk) (dsaPublic pk)+ sig =+ DSA.signDeterministic (SHAKE256 :: SHAKE256 2048) pk SHA256 ("m" :: ByteString)+ DSA.verify SHA256 pub sig ("m" :: ByteString) `shouldBe` True+ describe "hedged DSA" $ do+ let Vector _ pk _ = dsa2048+ pub = DSA.PublicKey (DSA.private_params pk) (dsaPublic pk)+ hedged+ (\m seed -> fst $ withDRG (drgNewTest seed) (DSA.sign pk SHA256 m))+ DSA.sign_r+ (\m sig -> DSA.verify SHA256 pub sig m)+ describe "hedged ECDSA" $ do+ let prx = Proxy :: Proxy ECC.Curve_P256R1+ d = throwCryptoError $ ECC.scalarFromInteger prx 0x1234567890abcdef+ q = ECDSA.toPublic prx d+ hedged+ (\m seed -> fst $ withDRG (drgNewTest seed) (ECDSA.sign prx d SHA256 m))+ (fst . ECDSA.signatureToIntegers prx)+ (\m sig -> ECDSA.verify prx SHA256 q sig m)+ describe "hedged ECDSA, Crypto.PubKey.ECC.ECDSA" $ do+ let curve = ECCT.getCurveByName ECCT.SEC_p384r1+ d = 0x1234567890abcdef+ priv = ECDSAOld.PrivateKey curve d+ pub = ECDSAOld.PublicKey curve (ECCG.generateQ curve d)+ hedged+ (\m seed -> fst $ withDRG (drgNewTest seed) (ECDSAOld.sign priv SHA256 m))+ ECDSAOld.sign_r+ (\m sig -> ECDSAOld.verify SHA256 pub sig m)+ where+ dsaPublic pk = DSA.calculatePublic (DSA.private_params pk) (DSA.private_x pk)
tests/SysDRGSpec.hs view
@@ -20,16 +20,42 @@ yield, ) import Control.Concurrent.MVar (newEmptyMVar, putMVar, takeMVar)-import Control.Exception (finally)+import Control.Exception (bracket_, finally) import Control.Monad (forM, forM_) import qualified Data.ByteString as BS import Data.List (group, nub, sort) import Test.Hspec -import Crypto.Random (getRandomBytes)+import Crypto.Random (+ SystemRandomMode (..),+ getRandomBytes,+ getSystemRandomMode,+ reseedSystem,+ setSystemRandomMode,+ ) spec :: Spec-spec = describe "the generator behind MonadRandom IO" $ do+spec = do+ describe "the mode" $ do+ it "is per draw by default" $+ getSystemRandomMode `shouldReturn` SystemRandomPerDraw+ it "reads back what was set" $+ inMode (SystemRandomPerThread 25) $+ getSystemRandomMode `shouldReturn` SystemRandomPerThread 25+ it "refuses a negative interval" $+ setSystemRandomMode (SystemRandomPerThread (-1))+ `shouldThrow` anyErrorCall+ describe "per draw" $ generator SystemRandomPerDraw+ describe "per thread" $ generator (SystemRandomPerThread 10)+ describe "per thread, no time limit" $ generator (SystemRandomPerThread 0)++-- | Run in a mode and go back to the default afterwards; hspec runs the+-- examples one at a time, so the process-wide setting is not raced.+inMode :: SystemRandomMode -> IO a -> IO a+inMode m = bracket_ (setSystemRandomMode m) (setSystemRandomMode SystemRandomPerDraw)++generator :: SystemRandomMode -> Spec+generator mode = around_ (inMode mode) $ do it "runs on more than one capability, or the rest proves little" $ do n <- getNumCapabilities n `shouldSatisfy` (> 1)@@ -92,6 +118,21 @@ (getRandomBytes 4096 :: IO BS.ByteString) >>= \b -> b `seq` return () second <- getRandomBytes 32 :: IO BS.ByteString second `shouldNotBe` first++ -- what a reseed does to the streams is for cbits/tests/sysdrg, which can+ -- save and restore a generator; here, that drawing goes on across one,+ -- from threads that drew before it+ it "goes on giving bytes across reseedSystem, on every thread" $ do+ earlier <- getRandomBytes 32 :: IO BS.ByteString+ reseedSystem+ dones <- forM [1 .. 8 :: Int] $ \_ -> do+ done <- newEmptyMVar+ _ <- forkIO $ (getRandomBytes 32 :: IO BS.ByteString) >>= putMVar done+ return done+ afters <- mapM takeMVar dones+ later <- getRandomBytes 32 :: IO BS.ByteString+ length (nub (earlier : later : afters)) `shouldBe` 10+ map BS.length (later : afters) `shouldBe` replicate 9 32 lengthCase :: Int -> Spec lengthCase n =
tests/forkprocess/ForkProcess.hs view
@@ -26,7 +26,11 @@ import System.Posix.IO (closeFd, createPipe, fdToHandle) import System.Posix.Process (ProcessStatus (..), forkProcess, getProcessStatus) -import Crypto.Random (getRandomBytes)+import Crypto.Random (+ SystemRandomMode (..),+ getRandomBytes,+ setSystemRandomMode,+ ) draw :: IO B.ByteString draw = getRandomBytes 32@@ -45,6 +49,15 @@ when (rtsSupportsBoundThreads && caps /= 1) $ die "this test needs one capability when threaded" + -- Per draw keeps nothing a child could inherit; per thread is the mode+ -- the fork handler is for, and the one that needs asking.+ mapM_ forkCheck [SystemRandomPerDraw, SystemRandomPerThread 0]+ where+ die msg = hPutStrLn stderr ("FAIL: " ++ msg) >> exitFailure++forkCheck :: SystemRandomMode -> IO ()+forkCheck mode = do+ setSystemRandomMode mode -- Before the fork, or the child inherits whatever is still in the -- buffer and writes it out again when it exits. hFlush stdout@@ -76,6 +89,6 @@ die ("the child sent " ++ show (B.length fromChild) ++ " bytes, not 32") when (fromChild == fromParent) $ die "parent and child drew the same bytes: the fork went unnoticed"- putStrLn "parent and child drew different bytes"+ putStrLn (show mode ++ ": parent and child drew different bytes") where die msg = hPutStrLn stderr ("FAIL: " ++ msg) >> exitFailure