crypton-x509 1.10.2 → 1.10.3
raw patch · 15 files changed
+721/−117 lines, 15 filesPVP ok
version bump matches the API change (PVP)
API changes (from Hackage documentation)
+ Data.X509: canonicalDistinguishedName :: DistinguishedName -> DistinguishedName
Files
- ChangeLog.md +16/−0
- Data/X509.hs +1/−0
- Data/X509/AlgorithmIdentifier.hs +65/−21
- Data/X509/CRL.hs +12/−15
- Data/X509/Cert.hs +15/−10
- Data/X509/DistinguishedName.hs +14/−3
- Data/X509/EC.hs +6/−0
- Data/X509/Ext.hs +66/−10
- Data/X509/ExtensionRaw.hs +10/−1
- Data/X509/Internal.hs +21/−0
- Data/X509/PrivateKey.hs +16/−12
- Data/X509/PublicKey.hs +44/−7
- Data/X509/Signed.hs +35/−30
- Tests/Tests.hs +398/−6
- crypton-x509.cabal +2/−2
ChangeLog.md view
@@ -1,5 +1,21 @@ # ChangeLog for crypton-x509 +## 1.10.3++Parsing is stricter: certificates with data after the public key,+duplicate extensions or trailing data are rejected.++* Omit AlgorithmIdentifier parameters for ECDSA and DSA signatures+ [#32](https://github.com/kazu-yamamoto/crypton-certificate/pull/32)+* Make certificate parsing stricter+ [#39](https://github.com/kazu-yamamoto/crypton-certificate/pull/39)+* Accept and encode valid structures in crypton-x509+ [#46](https://github.com/kazu-yamamoto/crypton-certificate/pull/46)+* Build certification paths with backtracking and implement CRL distribution points+ [#48](https://github.com/kazu-yamamoto/crypton-certificate/pull/48)+* Small fixes for EC keys, RSA verification and EKU+ [#50](https://github.com/kazu-yamamoto/crypton-certificate/pull/50)+ ## 1.10.2 * Reject iPAddress GeneralNames of invalid length in SubjectAltName
Data/X509.hs view
@@ -39,6 +39,7 @@ DnElement (..), ASN1CharacterString (..), getDnElement,+ canonicalDistinguishedName, -- * Certificate Chain module Data.X509.CertificateChain,
Data/X509/AlgorithmIdentifier.hs view
@@ -93,10 +93,6 @@ , ([1, 2, 840, 10045, 4, 3, 2], SignatureALG HashSHA256 PubKeyALG_EC) , ([1, 2, 840, 10045, 4, 3, 3], SignatureALG HashSHA384 PubKeyALG_EC) , ([1, 2, 840, 10045, 4, 3, 4], SignatureALG HashSHA512 PubKeyALG_EC)- , ([2, 16, 840, 1, 101, 3, 4, 2, 1], SignatureALG HashSHA256 PubKeyALG_RSAPSS)- , ([2, 16, 840, 1, 101, 3, 4, 2, 2], SignatureALG HashSHA384 PubKeyALG_RSAPSS)- , ([2, 16, 840, 1, 101, 3, 4, 2, 3], SignatureALG HashSHA512 PubKeyALG_RSAPSS)- , ([2, 16, 840, 1, 101, 3, 4, 2, 4], SignatureALG HashSHA224 PubKeyALG_RSAPSS) , ([2, 16, 840, 1, 101, 3, 4, 3, 1], SignatureALG HashSHA224 PubKeyALG_DSA) , ([2, 16, 840, 1, 101, 3, 4, 3, 2], SignatureALG HashSHA256 PubKeyALG_DSA) , ([1, 3, 101, 112], SignatureALG_IntrinsicHash PubKeyALG_Ed25519)@@ -115,6 +111,20 @@ ) ] +-- | Hash algorithms in RSASSA-PSS parameters.+pssHashTable :: [(OID, HashALG)]+pssHashTable =+ [ ([2, 16, 840, 1, 101, 3, 4, 2, 1], HashSHA256)+ , ([2, 16, 840, 1, 101, 3, 4, 2, 2], HashSHA384)+ , ([2, 16, 840, 1, 101, 3, 4, 2, 3], HashSHA512)+ , ([2, 16, 840, 1, 101, 3, 4, 2, 4], HashSHA224)+ ]++pssHashOID :: HashALG -> OID+pssHashOID h =+ maybe (error ("unknown PSS hash " ++ show h)) fst $+ find ((==) h . snd) pssHashTable+ oidSig :: OID -> SignatureALG oidSig oid = maybe (SignatureALG_Unknown oid) id $ lookup oid sig_table @@ -132,6 +142,11 @@ saltLen HashSHA224 = 28 saltLen _ = error "toASN1: X509.SignatureAlg.HashAlg: Unknown hash" +pss :: OID -> [ASN1] -> Either String (SignatureALG, [ASN1])+pss hash xs = case lookup hash pssHashTable of+ Just h -> Right (SignatureALG h PubKeyALG_RSAPSS, xs)+ Nothing -> Left ("fromASN1: X509.SignatureALG: unknown PSS hash " ++ show hash)+ instance ASN1Object SignatureALG where fromASN1 (Start Sequence : OID oid : Null : End Sequence : xs) = case oidSig oid of@@ -141,35 +156,41 @@ fromASN1 (Start Sequence : OID oid : End Sequence : xs) = Right (oidSig oid, xs) fromASN1- ( Start Sequence : OID [1, 2, 840, 113549, 1, 1, 10] : Start Sequence : Start _+ ( Start Sequence+ : OID [1, 2, 840, 113549, 1, 1, 10] : Start Sequence+ : Start (Container Context 0)+ : Start Sequence : OID hash1 : End Sequence- : End _- : Start _+ : End (Container Context 0)+ : Start (Container Context 1) : Start Sequence : OID [1, 2, 840, 113549, 1, 1, 8] : Start Sequence : OID _hash2 : End Sequence : End Sequence- : End _- : Start _+ : End (Container Context 1)+ : Start (Container Context 2) : IntVal _iv- : End _+ : End (Container Context 2) : End Sequence : End Sequence : xs ) =- Right (oidSig hash1, xs)+ pss hash1 xs fromASN1- ( Start Sequence : OID [1, 2, 840, 113549, 1, 1, 10] : Start Sequence : Start _+ ( Start Sequence+ : OID [1, 2, 840, 113549, 1, 1, 10] : Start Sequence+ : Start (Container Context 0)+ : Start Sequence : OID hash1 : Null : End Sequence- : End _- : Start _+ : End (Container Context 0)+ : Start (Container Context 1) : Start Sequence : OID [1, 2, 840, 113549, 1, 1, 8] : Start Sequence@@ -177,32 +198,49 @@ : Null : End Sequence : End Sequence- : End _- : Start _+ : End (Container Context 1)+ : Start (Container Context 2) : IntVal _iv- : End _+ : End (Container Context 2) : End Sequence : End Sequence : xs ) =- Right (oidSig hash1, xs)+ pss hash1 xs+ -- RSASSA-PSS with all parameters defaulted: SHA-1, MGF1 with SHA-1, salt 20+ fromASN1+ ( Start Sequence+ : OID [1, 2, 840, 113549, 1, 1, 10]+ : Start Sequence+ : End Sequence+ : End Sequence+ : xs+ ) =+ Right (SignatureALG HashSHA1 PubKeyALG_RSAPSS, xs) fromASN1 _ = Left "fromASN1: X509.SignatureALG: unknown format" toASN1 (SignatureALG_Unknown oid) = \xs -> Start Sequence : OID oid : Null : End Sequence : xs- toASN1 signatureAlg@(SignatureALG hashAlg PubKeyALG_RSAPSS) = \xs ->+ toASN1 (SignatureALG HashSHA1 PubKeyALG_RSAPSS) = \xs -> Start Sequence : OID [1, 2, 840, 113549, 1, 1, 10] : Start Sequence+ : End Sequence+ : End Sequence+ : xs+ toASN1 (SignatureALG hashAlg PubKeyALG_RSAPSS) = \xs ->+ Start Sequence+ : OID [1, 2, 840, 113549, 1, 1, 10]+ : Start Sequence : Start (Container Context 0) : Start Sequence- : OID (sigOID signatureAlg)+ : OID (pssHashOID hashAlg) : End Sequence : End (Container Context 0) : Start (Container Context 1) : Start Sequence : OID [1, 2, 840, 113549, 1, 1, 8] : Start Sequence- : OID (sigOID signatureAlg)+ : OID (pssHashOID hashAlg) : End Sequence : End Sequence : End (Container Context 1)@@ -213,4 +251,10 @@ : End Sequence : xs toASN1 signatureAlg@(SignatureALG_IntrinsicHash _) = \xs -> Start Sequence : OID (sigOID signatureAlg) : End Sequence : xs+ -- ECDSA: "the encoding MUST omit the parameters field"+ -- (RFC 5758 3.2, RFC 3279 2.2.3)+ toASN1 signatureAlg@(SignatureALG _ PubKeyALG_EC) = \xs -> Start Sequence : OID (sigOID signatureAlg) : End Sequence : xs+ -- DSA: "the encoding SHALL omit the parameters field"+ -- (RFC 5758 3.1, RFC 3279 2.2.2)+ toASN1 signatureAlg@(SignatureALG _ PubKeyALG_DSA) = \xs -> Start Sequence : OID (sigOID signatureAlg) : End Sequence : xs toASN1 signatureAlg = \xs -> Start Sequence : OID (sigOID signatureAlg) : Null : End Sequence : xs
Data/X509/CRL.hs view
@@ -16,7 +16,7 @@ ) where import Data.ASN1.Types-import Data.Hourglass (DateTime, TimezoneOffset (..))+import Data.Hourglass (DateTime) import Data.X509.AlgorithmIdentifier import Data.X509.DistinguishedName@@ -56,12 +56,12 @@ <*> (getNext >>= toTime) <*> getObject where- toTime (ASN1Time _ t _) = pure t+ toTime (ASN1Time _ t z) = pure (asn1TimeToUTC t z) toTime _ = throwParseError "bad revocation date" toASN1 (RevokedCertificate serial time crlEntryExtensions) = \xs -> [Start Sequence] ++ [IntVal serial]- ++ [ASN1Time TimeGeneralized time (Just (TimezoneOffset 0))]+ ++ [encodeASN1Time time] ++ toASN1 crlEntryExtensions [] ++ [End Sequence] ++ xs@@ -76,7 +76,8 @@ parseCRL :: ParseASN1 CRL parseCRL = do CRL- <$> (getNext >>= getVersion)+ -- the version is absent in v1 CRLs+ <$> (maybe 0 id <$> getNextMaybe getVersion) <*> getObject <*> getObject <*> (getNext >>= getThisUpdate)@@ -84,15 +85,15 @@ <*> parseRevokedCertificates <*> parseCRLExtensions where- getVersion (IntVal v) = return $ fromIntegral v- getVersion _ = throwParseError "unexpected type for version"+ getVersion (IntVal v) = Just v+ getVersion _ = Nothing - getThisUpdate (ASN1Time _ t1 _) = return t1+ getThisUpdate (ASN1Time _ t1 z) = return (asn1TimeToUTC t1 z) getThisUpdate _ = throwParseError "bad this update format, expecting time" getNextUpdate = getNextMaybe timeOrNothing - timeOrNothing (ASN1Time _ tnext _) = Just tnext+ timeOrNothing (ASN1Time _ tnext z) = Just (asn1TimeToUTC tnext z) timeOrNothing _ = Nothing parseRevokedCertificates :: ParseASN1 [RevokedCertificate]@@ -108,15 +109,11 @@ encodeCRL :: CRL -> ASN1S encodeCRL crl xs =- [IntVal $ crlVersion crl]+ [IntVal (crlVersion crl) | crlVersion crl /= 0] ++ toASN1 (crlSignatureAlg crl) [] ++ toASN1 (crlIssuer crl) []- ++ [ASN1Time TimeGeneralized (crlThisUpdate crl) (Just (TimezoneOffset 0))]- ++ ( maybe- []- (\t -> [ASN1Time TimeGeneralized t (Just (TimezoneOffset 0))])- (crlNextUpdate crl)- )+ ++ [encodeASN1Time (crlThisUpdate crl)]+ ++ maybe [] (\t -> [encodeASN1Time t]) (crlNextUpdate crl) ++ maybeRevoked (crlRevokedCertificates crl) ++ maybeCrlExts (crlExtensions crl) ++ xs
Data/X509/Cert.hs view
@@ -62,7 +62,9 @@ parseCertHeaderVersion = maybe 0 id <$> onNextContainerMaybe (Container Context 0) (getNext >>= getVer) where- getVer (IntVal v) = return $ fromIntegral v+ getVer (IntVal v)+ | v >= 0 && v <= 2 = return $ fromIntegral v+ | otherwise = throwParseError ("unsupported version " ++ show v) getVer _ = throwParseError "unexpected type for version" parseCertHeaderSerial :: ParseASN1 Integer@@ -75,7 +77,8 @@ parseCertHeaderValidity :: ParseASN1 (DateTime, DateTime) parseCertHeaderValidity = getNextContainer Sequence >>= toTimeBound where- toTimeBound [ASN1Time _ t1 _, ASN1Time _ t2 _] = return (t1, t2)+ toTimeBound [ASN1Time _ t1 z1, ASN1Time _ t2 z2] =+ return (asn1TimeToUTC t1 z1, asn1TimeToUTC t2 z2) toTimeBound _ = throwParseError "bad validity format" -- | parse header structure of a x509 certificate. the structure is the following:@@ -99,6 +102,14 @@ adapt (Just e) = e adapt Nothing = Extensions Nothing +-- | issuerUniqueID and subjectUniqueID are skipped.+parseUniqueIDs :: ParseASN1 ()+parseUniqueIDs = uid 1 >> uid 2 >> return ()+ where+ uid n = getNextMaybe (\a -> if isUID n a then Just () else Nothing)+ isUID n (Other Context m _) = n == m+ isUID _ _ = False+ parseCertificate :: ParseASN1 Certificate parseCertificate = Certificate@@ -108,7 +119,7 @@ <*> getObject <*> parseCertHeaderValidity <*> getObject- <*> getObject+ <*> (getObject <* parseUniqueIDs) <*> parseExtensions encodeCertificateHeader :: Certificate -> [ASN1]@@ -131,15 +142,9 @@ eValidity = asn1Container Sequence- [ ASN1Time (timeType t1) t1 (Just (TimezoneOffset 0))- , ASN1Time (timeType t2) t2 (Just (TimezoneOffset 0))- ]+ [encodeASN1Time t1, encodeASN1Time t2] eSubject = toASN1 (certSubjectDN cert) [] epkinfo = toASN1 (certPubKey cert) [] eexts = case certExtensions cert of Extensions Nothing -> [] exts -> asn1Container (Container Context 3) $ toASN1 exts []- timeType t =- if t >= timeConvert (Date 2050 January 1)- then TimeGeneralized- else TimeUTC
Data/X509/DistinguishedName.hs view
@@ -15,14 +15,14 @@ -- Distinguished Name Elements DnElement (..), getDnElement,+ canonicalDistinguishedName, ) where -#if MIN_VERSION_base(4,9,0)+#if !(MIN_VERSION_base(4,11,0)) import Data.Semigroup-#else-import Data.Monoid #endif import Data.ASN1.Types+import Data.Char (toLower) import Data.X509.Internal -- | A list of OID and strings.@@ -53,6 +53,17 @@ -- | Try to get a specific element in a 'DistinguishedName' structure getDnElement :: DnElement -> DistinguishedName -> Maybe ASN1CharacterString getDnElement element (DistinguishedName els) = lookup (getObjectID element) els++-- | A form for comparing names (RFC 5280 7.1): string values are+-- converted to UTF8String, lower-cased and whitespace is folded. Values+-- that cannot be decoded are kept.+canonicalDistinguishedName :: DistinguishedName -> DistinguishedName+canonicalDistinguishedName (DistinguishedName els) =+ DistinguishedName [(oid, canon v) | (oid, v) <- els]+ where+ canon v = case safeCharacterToString v of+ Just str -> asn1CharacterString UTF8 $ unwords $ words $ map toLower str+ Nothing -> v -- | Only use to encode a DistinguishedName without including it in a -- Sequence
Data/X509/EC.hs view
@@ -84,7 +84,10 @@ ECC.ecc_a cc == pubkeyEC_a pub && ECC.ecc_b cc == pubkeyEC_b pub && ECC.ecc_n cc == pubkeyEC_order pub+ && ECC.ecc_h cc == pubkeyEC_cofactor pub && p == pubkeyEC_prime pub+ && unserializePoint (ECC.getCurveByName c) (pubkeyEC_generator pub)+ == Just (ECC.ecc_g cc) _ -> False -- | Return the EC curve associated to an EC Private Key. This does not check@@ -120,7 +123,10 @@ ECC.ecc_a cc == privkeyEC_a priv && ECC.ecc_b cc == privkeyEC_b priv && ECC.ecc_n cc == privkeyEC_order priv+ && ECC.ecc_h cc == privkeyEC_cofactor priv && p == privkeyEC_prime priv+ && unserializePoint (ECC.getCurveByName c) (privkeyEC_generator priv)+ == Just (ECC.ecc_g cc) _ -> False -- | Return the curve name associated to an OID
Data/X509/Ext.hs view
@@ -43,7 +43,7 @@ import Data.ASN1.Encoding import Data.ASN1.Parse import Data.ASN1.Types-import Data.Bits (shiftR, testBit, (.&.))+import Data.Bits (bit, shiftR, testBit, (.&.), (.|.)) import qualified Data.ByteString as B import qualified Data.ByteString.Char8 as BC import Data.List (find)@@ -51,7 +51,7 @@ import Data.Proxy import Data.X509.DistinguishedName import Data.X509.ExtensionRaw-import Data.X509.Internal (safeCharacterToString, safeDecode)+import Data.X509.Internal (asn1Container, safeCharacterToString, safeDecode) -- | key usage flag that is found in the key usage extension field. data ExtKeyUsageFlag@@ -150,6 +150,10 @@ | otherwise = Left "invalid pathlen" extDecode [Start Sequence, Boolean b, End Sequence] = Right (ExtBasicConstraints b Nothing) extDecode [Start Sequence, End Sequence] = Right (ExtBasicConstraints False Nothing)+ -- cA is omitted when FALSE (DER)+ extDecode [Start Sequence, IntVal v, End Sequence]+ | v >= 0 = Right (ExtBasicConstraints False (Just v))+ | otherwise = Left "invalid pathlen" extDecode _ = Left "unknown sequence" -- | Describe key usage@@ -260,8 +264,17 @@ extHasNestedASN1 = const True extEncode (ExtAuthorityKeyId keyid) = [Start Sequence, Other Context 0 keyid, End Sequence]- extDecode [Start Sequence, Other Context 0 keyid, End Sequence] =- Right $ ExtAuthorityKeyId keyid++ -- authorityCertIssuer and authorityCertSerialNumber are not kept+ extDecode (Start Sequence : Other Context 0 keyid : rest)+ | issuerSerial rest = Right $ ExtAuthorityKeyId keyid+ where+ issuerSerial [End Sequence] = True+ issuerSerial (Start (Container Context 1) : xs) =+ case dropWhile (/= End (Container Context 1)) xs of+ _ : [Other Context 2 _, End Sequence] -> True+ _ -> False+ issuerSerial _ = False extDecode _ = Left "unknown sequence" -- | Identify how CRL information is obtained@@ -290,10 +303,46 @@ instance Extension ExtCrlDistributionPoints where extOID _ = [2, 5, 29, 31] extHasNestedASN1 = const True- extEncode = error "extEncode ExtCrlDistributionPoints unimplemented"- extDecode _ = Left "extDecode ExtCrlDistributionPoints unimplemented"---- extEncode (ExtCrlDistributionPoints )+ extEncode (ExtCrlDistributionPoints dps) =+ asn1Container Sequence $ concatMap encodeDP dps+ where+ encodeDP dp = asn1Container Sequence $ asn1Container (Container Context 0) $ case dp of+ DistributionPointFullName names ->+ asn1Container (Container Context 0) $ concatMap encodeAltName names+ DistributionNameRelative (DistinguishedName els) ->+ asn1Container (Container Context 1) $+ concat [asn1Container Sequence [OID o, ASN1String v] | (o, v) <- els]+ extDecode = runParseASN1 (ExtCrlDistributionPoints <$> parseDPs)+ where+ parseDPs = onNextContainer Sequence $ do+ dps <- getMany parseDP+ when (null dps) $ throwParseError "CRLDistributionPoints: empty"+ return $ catMaybes dps+ -- only the distribution point name is kept: reasons and cRLIssuer+ -- are dropped, and so are points without a name+ parseDP = onNextContainer Sequence $ do+ name <- onNextContainerMaybe (Container Context 0) parseName+ _ <- getNextMaybe reasons+ _ <- onNextContainerMaybe (Container Context 2) (getMany getAddrMaybe)+ return name+ parseName = do+ full <-+ onNextContainerMaybe (Container Context 0) (catMaybes <$> getMany getAddrMaybe)+ case full of+ Just names -> return $ DistributionPointFullName names+ Nothing ->+ maybe (throwParseError "DistributionPoint: unknown name") return+ =<< onNextContainerMaybe+ (Container Context 1)+ (DistributionNameRelative . DistinguishedName <$> getMany parseATV)+ parseATV = onNextContainer Sequence $ do+ o <- getNext+ v <- getNext+ case (o, v) of+ (OID oid, ASN1String str) -> return (oid, str)+ _ -> throwParseError "DistributionPoint: invalid attribute"+ reasons (Other Context 1 _) = Just ()+ reasons _ = Nothing -- | GeneralName types that 'AltName' cannot represent are skipped. parseGeneralNames :: ParseASN1 [AltName]@@ -412,10 +461,17 @@ dataLen = 8 * fromIntegral (B.length (bitArrayGetData bits)) len = minimum [bitArrayLength bits, dataLen, fromIntegral (fromEnum lastFlag) + 1] +-- | DER: trailing zero bits are removed. flagsToBits :: Enum a => [a] -> BitArray-flagsToBits flags = foldl bitArraySetBit bitArrayEmpty $ map (fromIntegral . fromEnum) flags+flagsToBits flags = toBitArray (B.pack bytes) (8 * nbytes - len) where- bitArrayEmpty = toBitArray (B.pack [0, 0]) 7+ ixs = map fromEnum flags+ len = if null ixs then 0 else maximum ixs + 1+ nbytes = (len + 7) `div` 8+ bytes =+ [ foldl (.|.) 0 [bit (7 - i `mod` 8) | i <- ixs, i `div` 8 == n]+ | n <- [0 .. nbytes - 1]+ ] data ExtNetscapeComment = ExtNetscapeComment B.ByteString deriving (Show, Eq)
Data/X509/ExtensionRaw.hs view
@@ -17,6 +17,7 @@ import Data.ASN1.Encoding import Data.ASN1.Types import qualified Data.ByteString as B+import Data.List (nub) import Data.X509.Internal -- | An undecoded extension@@ -55,7 +56,15 @@ asn1Container Sequence (concatMap encodeExt exts) ++ xs fromASN1 s = runParseASN1State (Extensions <$> parseExtensions) s where- parseExtensions = onNextContainerMaybe Sequence (getMany getObject)+ -- RFC 5280: at most one instance of a particular extension+ parseExtensions = do+ mexts <- onNextContainerMaybe Sequence (getMany getObject)+ case mexts of+ Just exts+ | let oids = map extRawOID exts+ , length (nub oids) /= length oids ->+ throwParseError "fromASN1: X509.Extensions: duplicate extension"+ _ -> return mexts instance ASN1Object ExtensionRaw where toASN1 extraw = \xs -> encodeExt extraw ++ xs
Data/X509/Internal.hs view
@@ -16,6 +16,10 @@ runErrT, safeDecode, safeCharacterToString,++ -- * time+ asn1TimeToUTC,+ encodeASN1Time, ) where import Control.Exception (@@ -29,12 +33,29 @@ import Control.Monad.Trans.Except import Data.ASN1.Parse import Data.ASN1.Types+import Data.Hourglass import qualified Data.List as L import System.IO.Unsafe (unsafeDupablePerformIO) runErrT :: ExceptT e m a -> m (Either e a) runErrT = runExceptT type ErrT = ExceptT++-- | A decoded time converted to UTC with its zone offset.+asn1TimeToUTC :: DateTime -> Maybe TimezoneOffset -> DateTime+asn1TimeToUTC t (Just (TimezoneOffset m))+ | m /= 0 = timeAdd t (Seconds (fromIntegral (negate m) * 60))+asn1TimeToUTC t _ = t++-- | RFC 5280 4.1.2.5: UTCTime through 2049 from 1950, GeneralizedTime+-- otherwise.+encodeASN1Time :: DateTime -> ASN1+encodeASN1Time t = ASN1Time ty t (Just (TimezoneOffset 0))+ where+ y = dateYear (dtDate t)+ ty+ | y >= 1950 && y < 2050 = TimeUTC+ | otherwise = TimeGeneralized -- | create a container around the stream of ASN1 asn1Container :: ASN1ConstructionType -> [ASN1] -> [ASN1]
Data/X509/PrivateKey.hs view
@@ -32,12 +32,14 @@ import Data.ASN1.Types import Data.X509.AlgorithmIdentifier+import Data.X509.Internal (safeDecode) import Data.X509.OID (curvesOIDTable, lookupByOID, lookupOID) import Data.X509.PublicKey (SerializedPoint (..)) import Crypto.Debug (DebugShow (..), debugShowBytes) import Crypto.Error (CryptoFailable (..))-import Crypto.Number.Serialize (i2osp, os2ip)+import Crypto.Number.Basic (numBytes)+import Crypto.Number.Serialize (i2osp, i2ospOf_, os2ip) import qualified Crypto.PubKey.Curve25519 as X25519 import qualified Crypto.PubKey.Curve448 as X448 import qualified Crypto.PubKey.DSA as DSA@@ -296,10 +298,10 @@ : End Sequence : as ) = do- asn1 <- mapLeft failure (decodeASN1' BER bytes)+ asn1 <- mapLeft failure (safeDecode $ decodeASN1' BER bytes) fmap (const as) <$> rsaFromASN1 asn1 where- failure = ("rsaFromASN1: " ++) . show+ failure = ("rsaFromASN1: " ++) rsaFromASN1 _ = Left "rsaFromASN1: unexpected format" dsaFromASN1 :: [ASN1] -> Either String (DSA.PrivateKey, [ASN1])@@ -323,10 +325,10 @@ : OctetString bytes : End Sequence : as- ) = case decodeASN1' BER bytes of+ ) = case safeDecode $ decodeASN1' BER bytes of Right [IntVal x] -> pure (DSA.PrivateKey (DSA.Params p g q) x, as) Right _ -> Left "DSA.PrivateKey.fromASN1: unexpected format"- Left e -> Left $ "DSA.PrivateKey.fromASN1: " ++ show e+ Left e -> Left $ "DSA.PrivateKey.fromASN1: " ++ e dsaFromASN1 _ = Left "DSA.PrivateKey.fromASN1: unexpected format" ecdsaFromASN1 :: [ASN1] -> Either String (PrivKeyEC, [ASN1])@@ -380,7 +382,7 @@ : rest ) = case rest' of (OctetString bytes : rest'') -> do- asn1 <- mapLeft (failing . show) (decodeASN1' BER bytes)+ asn1 <- mapLeft failing (safeDecode $ decodeASN1' BER bytes) fmap (const rest'') <$> go (oid ++ acc) asn1 _ -> Left $ failing "unexpected EC format" where@@ -417,18 +419,18 @@ case getP oid of Just (name, parse) -> do let err s = Left (name ++ ".SecretKey.fromASN1: " ++ s)- case decodeASN1' BER bs of+ case safeDecode $ decodeASN1' BER bs of Right [OctetString key] -> case parse key of CryptoPassed s -> Right (s, zs) CryptoFailed e -> err ("invalid secret key: " ++ show e) Right _ -> err "unexpected inner format"- Left e -> err (show e)+ Left e -> err e Nothing -> case getMLDSA oid of Just (name, parse) ->- case decodeASN1' BER bs of+ case safeDecode $ decodeASN1' BER bs of Right inner -> (\k -> (k, zs)) <$> parse inner- Left e -> Left (name ++ ".SigningKey.fromASN1: " ++ show e)+ Left e -> Left (name ++ ".SigningKey.fromASN1: " ++ e) Nothing -> Left ("newcurveFromASN1: unexpected OID " ++ show oid) _ -> Left "newcurveFromASN1: unexpected end format" | otherwise = Left ("newcurveFromASN1: unexpected version: " ++ show v)@@ -544,17 +546,19 @@ x = DSA.calculatePublic params y ecdsaToASN1 :: PrivKeyEC -> ASN1S+-- RFC 5915: the private key is as long as the curve order. ecdsaToASN1 (PrivKeyEC_Named curveName d) = (++) [ Start Sequence , IntVal 1- , OctetString (i2osp d)+ , OctetString (i2ospOf_ (numBytes order) d) , Start (Container Context 0) , OID oid , End (Container Context 0) , End Sequence ] where+ order = ECC.ecc_n $ ECC.common_curve $ ECC.getCurveByName curveName err = error . ("ECDSA.PrivateKey.toASN1: " ++) oid = fromMaybe@@ -564,7 +568,7 @@ (++) [ Start Sequence , IntVal 1- , OctetString (i2osp d)+ , OctetString (i2ospOf_ (numBytes o) d) , Start (Container Context 0) , Start Sequence , IntVal 1
Data/X509/PublicKey.hs view
@@ -28,7 +28,7 @@ import Crypto.Error (CryptoFailable (..)) import Crypto.Number.Basic (numBytes)-import Crypto.Number.Serialize (os2ip)+import Crypto.Number.Serialize (i2osp, i2ospOf_, os2ip) import qualified Crypto.PubKey.Curve25519 as X25519 import qualified Crypto.PubKey.Curve448 as X448 import qualified Crypto.PubKey.DSA as DSA@@ -203,8 +203,17 @@ case xs of End Sequence : BitString bits : End Sequence : xs2 -> decodeCF "ML-DSA-87" PubKeyMLDSA87 bits xs2 MLDSA.verificationKey _ -> Left ("fromASN1: X509.PubKey: unknown ML-DSA-87 format: " ++ show xs)- | otherwise = Left $ "fromASN1: unknown public key OID: " ++ show pkalg+ -- parameters of unknown algorithms are not kept+ | otherwise = case dropParams (0 :: Int) xs of+ BitString bits : End Sequence : xs2 ->+ Right (PubKeyUnknown pkalg (bitArrayGetData bits), xs2)+ _ -> Left ("fromASN1: X509.PubKey: unknown format for " ++ show pkalg) where+ dropParams 0 (End Sequence : r) = r+ dropParams n (Start _ : r) = dropParams (n + 1) r+ dropParams n (End _ : r) = dropParams (n - 1) r+ dropParams n (_ : r) = dropParams n r+ dropParams _ [] = [] decodeASN1Err format bits xs2 f = case safeDecode (decodeASN1' BER (bitArrayGetData bits)) of Left err ->@@ -212,7 +221,10 @@ ("fromASN1: X509.PubKey " ++ format ++ " bitarray cannot be parsed: " ++ err) Right s -> case f s of Left err -> Left err- Right (r, xsinner) -> Right (r, xsinner ++ xs2)+ Right (r, []) -> Right (r, xs2)+ -- anything after the key must not leak into the outer stream+ Right _ ->+ Left ("fromASN1: X509.PubKey " ++ format ++ " bitarray has trailing data") toPubKeyRSA = either Left (\(rsaKey, r) -> Right (PubKeyRSA rsaKey, r)) bitArrayToPoint = SerializedPoint . bitArrayGetData@@ -273,8 +285,28 @@ eOid = case lookupOID curvesOIDTable curveName of Just oid -> oid _ -> error ("undefined curve OID: " ++ show curveName)- encodeInner (PubKeyEC (PubKeyEC_Prime{})) =- error "encodeInner: unimplemented public key EC_Prime"+ encodeInner (PubKeyEC k@PubKeyEC_Prime{}) =+ asn1Container Sequence ([pkalg] ++ params) ++ [BitString $ toBitArray pub 0]+ where+ SerializedPoint pub = pubkeyEC_pub k+ SerializedPoint gen = pubkeyEC_generator k+ size = numBytes (pubkeyEC_prime k)+ params =+ asn1Container Sequence $+ [IntVal 1]+ ++ asn1Container+ Sequence+ [OID [1, 2, 840, 10045, 1, 1], IntVal (pubkeyEC_prime k)]+ ++ asn1Container+ Sequence+ [ OctetString (i2ospOf_ size (pubkeyEC_a k))+ , OctetString (i2ospOf_ size (pubkeyEC_b k))+ , BitString $ toBitArray (i2osp (pubkeyEC_seed k)) 0+ ]+ ++ [ OctetString gen+ , IntVal (pubkeyEC_order k)+ , IntVal (pubkeyEC_cofactor k)+ ] encodeInner (PubKeyX25519 pubkey) = asn1Container Sequence [pkalg] ++ [BitString $ toBitArray (convert pubkey) 0] encodeInner (PubKeyX448 pubkey) =@@ -330,7 +362,10 @@ | otherwise = let inner = either strError rsaPubFromASN1 $ safeDecode $ decodeASN1' BER bs strError = Left . ("fromASN1: RSA.PublicKey: " ++)- in either Left (\(k, _) -> Right (k, xs)) inner+ in case inner of+ Right (k, []) -> Right (k, xs)+ Right _ -> Left "fromASN1: RSA.PublicKey: trailing data"+ Left e -> Left e rsaPubFromASN1 _ = Left "fromASN1: RSA.PublicKey: unexpected format" @@ -343,7 +378,9 @@ where uintOfBytes = foldl (\acc n -> (acc `shiftL` 8) + fromIntegral n) 0 bytesOfInt :: Integer -> [Word8]- bytesOfInt n = if testBit (head nints) 7 then nints else 0xff : nints+ bytesOfInt n = case nints of+ h : _ | testBit h 7 -> nints+ _ -> 0xff : nints where nints = reverse $ plusOne $ reverse $ map complement $ bytesOfUInt (abs n) plusOne [] = [1]
Data/X509/Signed.hs view
@@ -170,34 +170,39 @@ where -- the following implementation is very inefficient. -- uses reverse and containing, move to a better solution eventually- parseSigned l = onContainer (fst $ getConstructedEndRepr l) $ \l2 ->- let (objRepr, rem1) = getConstructedEndRepr l2- (sigAlgSeq, rem2) = getConstructedEndRepr rem1- (sigSeq, _) = getConstructedEndRepr rem2- obj = onContainer objRepr (either Left Right . fromASN1 . map fst)- in case (obj, map fst sigSeq) of- (Right (o, []), [BitString signature]) ->- let rawObj = Raw.toByteString $ concatMap snd objRepr- in case fromASN1 $ map fst sigAlgSeq of- Left s -> Left ("signed object error sigalg: " ++ s)- Right (sigAlg, _) ->- let signed =- Signed- { signedObject = o- , signedAlg = sigAlg- , signedSignature = bitArrayGetData signature- }- in Right $- SignedExact- { getSigned = signed- , exactObjectRaw = rawObj- , encodeSignedObject = b- }- (Right (_, remObj), _) ->- Left $ ("signed object error: remaining stream in object: " ++ show remObj)- (Left err, _) -> Left $ ("signed object error: " ++ show err)- onContainer ((Start _, _) : l) f =+ parseSigned l = case getConstructedEndRepr l of+ (outer, []) -> onSequence outer $ \l2 ->+ let (objRepr, rem1) = getConstructedEndRepr l2+ (sigAlgSeq, rem2) = getConstructedEndRepr rem1+ (sigSeq, rem3) = getConstructedEndRepr rem2+ obj = onSequence objRepr (fromASN1 . map fst)+ in case (obj, map fst sigSeq) of+ _ | not (null rem3) -> Left "signed object error: trailing data"+ (Right (o, []), [BitString signature]) ->+ let rawObj = Raw.toByteString $ concatMap snd objRepr+ in case fromASN1 $ map fst sigAlgSeq of+ Left err -> Left ("signed object error sigalg: " ++ err)+ Right (sigAlg, []) ->+ let signed =+ Signed+ { signedObject = o+ , signedAlg = sigAlg+ , signedSignature = bitArrayGetData signature+ }+ in Right $+ SignedExact+ { getSigned = signed+ , exactObjectRaw = rawObj+ , encodeSignedObject = b+ }+ Right _ -> Left "signed object error sigalg: trailing data"+ (Right (_, []), _) -> Left "signed object error: invalid signature"+ (Right (_, remObj), _) ->+ Left $ ("signed object error: remaining stream in object: " ++ show remObj)+ (Left err, _) -> Left $ ("signed object error: " ++ err)+ _ -> Left "signed object error: trailing data"+ onSequence ((Start Sequence, _) : l) f = case reverse l of- ((End _, _) : l2) -> f $ reverse l2- _ -> f []- onContainer _ f = f []+ ((End Sequence, _) : l2) -> f $ reverse l2+ _ -> Left "signed object error: invalid sequence"+ onSequence _ _ = Left "signed object error: expecting a sequence"
Tests/Tests.hs view
@@ -11,9 +11,11 @@ import Crypto.Debug (DebugShow (..)) import Crypto.Error (throwCryptoError)+import Crypto.Number.Serialize (i2ospOf_) import qualified Crypto.PubKey.Curve25519 as X25519 import qualified Crypto.PubKey.Curve448 as X448 import qualified Crypto.PubKey.DSA as DSA+import qualified Crypto.PubKey.ECC.Prim as ECC import qualified Crypto.PubKey.ECC.Types as ECC import qualified Crypto.PubKey.Ed25519 as Ed25519 import qualified Crypto.PubKey.Ed448 as Ed448@@ -28,6 +30,7 @@ import Data.Maybe (fromJust) import Data.Proxy (Proxy (..)) import Data.X509+import Data.X509.EC (ecPubKeyCurveName) import MLDSAKeys @@ -188,10 +191,9 @@ <$> oneof [ pure Nothing , Just- <$> ( listOf1 $- oneof- [ extensionEncode <$> arbitrary <*> (arbitrary :: Gen ExtKeyUsage)- ]+ -- at most one instance of an extension+ <$> ( (: [])+ <$> (extensionEncode <$> arbitrary <*> (arbitrary :: Gen ExtKeyUsage)) ) ] @@ -484,6 +486,16 @@ instance Arbitrary ExtSubjectAltName where arbitrary = ExtSubjectAltName <$> arbitrary +instance Arbitrary DistributionPoint where+ arbitrary =+ oneof+ [ DistributionPointFullName <$> listOf1 arbitrary+ , DistributionNameRelative <$> arbitrary+ ]++instance Arbitrary ExtCrlDistributionPoints where+ arbitrary = ExtCrlDistributionPoints <$> listOf1 arbitrary+ -- NameConstraints with permitted dNSName "example.com" and -- excluded iPAddress 10.0.0.0/8, as encoded by OpenSSL. property_name_constraints_der :: Bool@@ -588,9 +600,348 @@ (\_ -> (B.pack [1], SignatureALG HashSHA256 PubKeyALG_RSA, ())) cert -- replace the first character of the first UTCTime with a non-ASCII byte- (before, after) = B.breakSubstring (B.pack [0x17, 0x0d]) encoded- corrupted = before <> B.pack [0x17, 0x0d, 0xff] <> B.drop 3 after+ (before, rest) = B.breakSubstring (B.pack [0x17, 0x0d]) encoded+ corrupted = before <> B.pack [0x17, 0x0d, 0xff] <> B.drop 3 rest +-- | A certificate re-encoded after modifying its ASN.1 stream.+modifiedCertificate :: ([ASN1] -> [ASN1]) -> Either String SignedCertificate+modifiedCertificate f = decodeSignedCertificate $ encodeASN1' DER $ f asn1+ where+ t = timeConvert (Date 2020 January 1) :: DateTime+ dn = DistinguishedName [(getObjectID DnCommonName, asn1CharacterString UTF8 "x")]+ cert =+ Certificate+ 2+ 1+ (SignatureALG HashSHA256 PubKeyALG_RSA)+ dn+ (t, t)+ dn+ (PubKeyRSA (RSA.PublicKey 1 0x7f 3))+ (Extensions Nothing)+ encoded =+ encodeSignedObject $+ fst $+ objectToSignedExact+ (\_ -> (B.pack [1], SignatureALG HashSHA256 PubKeyALG_RSA, ()))+ cert+ asn1 = either (error . show) id $ decodeASN1' DER encoded++isLeft' :: Either a b -> Bool+isLeft' = either (const True) (const False)++property_signed_strict :: Bool+property_signed_strict =+ not (isLeft' (modifiedCertificate id))+ && isLeft' (modifiedCertificate (++ [IntVal 1]))+ && isLeft' (modifiedCertificate (\l -> init l ++ [IntVal 1, End Sequence]))+ && isLeft' (modifiedCertificate (\l -> Start Set : init (drop 1 l) ++ [End Set]))++property_duplicate_extensions :: Bool+property_duplicate_extensions =+ isLeft'+ ( fromASN1 (toASN1 (Extensions (Just [e, e])) [])+ :: Either String (Extensions, [ASN1])+ )+ where+ e = extensionEncode False (ExtKeyUsage [KeyUsage_digitalSignature])++-- Data after the RSA key in the BIT STRING must not be parsed as+-- following fields.+property_rsa_pubkey_trailing :: Bool+property_rsa_pubkey_trailing =+ not (isLeft' (decode key)) && isLeft' (decode (key ++ [IntVal 1]))+ where+ key = [Start Sequence, IntVal 0xc5, IntVal 3, End Sequence]+ decode k =+ fromASN1+ [ Start Sequence+ , Start Sequence+ , OID [1, 2, 840, 113549, 1, 1, 1]+ , Null+ , End Sequence+ , BitString (toBitArray (encodeASN1' DER k) 0)+ , End Sequence+ ]+ :: Either String (PubKey, [ASN1])++property_pss_hash :: Bool+property_pss_hash =+ decode (pss [2, 16, 840, 1, 101, 3, 4, 2, 1])+ == Right (SignatureALG HashSHA256 PubKeyALG_RSAPSS, [])+ -- sha256WithRSAEncryption is not a hash algorithm+ && isLeft' (decode (pss [1, 2, 840, 113549, 1, 1, 11]))+ -- a bare hash algorithm is not a signature algorithm+ && decode [Start Sequence, OID sha256, End Sequence]+ == Right (SignatureALG_Unknown sha256, [])+ && decode (toASN1 (SignatureALG HashSHA384 PubKeyALG_RSAPSS) [])+ == Right (SignatureALG HashSHA384 PubKeyALG_RSAPSS, [])+ where+ sha256 = [2, 16, 840, 1, 101, 3, 4, 2, 1]+ decode l = fromASN1 l :: Either String (SignatureALG, [ASN1])+ pss h =+ [ Start Sequence+ , OID [1, 2, 840, 113549, 1, 1, 10]+ , Start Sequence+ , Start (Container Context 0)+ , Start Sequence+ , OID h+ , End Sequence+ , End (Container Context 0)+ , Start (Container Context 1)+ , Start Sequence+ , OID [1, 2, 840, 113549, 1, 1, 8]+ , Start Sequence+ , OID h+ , End Sequence+ , End Sequence+ , End (Container Context 1)+ , Start (Container Context 2)+ , IntVal 32+ , End (Container Context 2)+ , End Sequence+ , End Sequence+ ]++-- Malformed inner encodings of PKCS#8 keys return Left, not an exception.+property_privkey_malformed :: Bool+property_privkey_malformed =+ all+ isLeft'+ [ decode [1, 2, 840, 113549, 1, 1, 1] Null rsaInner+ , decode [1, 3, 101, 112] none edInner+ ]+ where+ rsaInner = B.pack [0x30, 0x05, 0x02, 0x00, 0x02, 0x01, 0x00]+ edInner = B.pack [0x17, 0x01, 0xff]+ none = End Sequence+ decode oid param inner =+ fromASN1+ ( [Start Sequence, IntVal 0, Start Sequence, OID oid]+ ++ (if param == none then [] else [param])+ ++ [End Sequence, OctetString inner, End Sequence]+ )+ :: Either String (PrivKey, [ASN1])++sampleCert :: Certificate+sampleCert =+ Certificate+ 2+ 1+ (SignatureALG HashSHA256 PubKeyALG_RSA)+ dn+ (t, t)+ dn+ (PubKeyRSA (RSA.PublicKey 1 0x7f 3))+ (Extensions Nothing)+ where+ t = timeConvert (Date 2020 January 1) :: DateTime+ dn = DistinguishedName [(getObjectID DnCommonName, asn1CharacterString UTF8 "x")]++decodeCert :: [ASN1] -> Either String (Certificate, [ASN1])+decodeCert = fromASN1++property_key_usage_der :: Bool+property_key_usage_der =+ extEncodeBs (ExtKeyUsage [KeyUsage_digitalSignature]) == B.pack [3, 2, 7, 0x80]+ && extEncodeBs (ExtKeyUsage [KeyUsage_keyCertSign, KeyUsage_cRLSign])+ == B.pack [3, 2, 1, 0x06]+ && extEncodeBs (ExtKeyUsage [KeyUsage_digitalSignature, KeyUsage_decipherOnly])+ == B.pack [3, 3, 7, 0x80, 0x80]+ && extEncodeBs (ExtKeyUsage []) == B.pack [3, 1, 0]++property_basic_constraints_no_ca :: Bool+property_basic_constraints_no_ca =+ extDecode [Start Sequence, IntVal 0, End Sequence]+ == Right (ExtBasicConstraints False (Just 0))++property_aki_issuer_serial :: Bool+property_aki_issuer_serial =+ extDecode+ ( [Start Sequence, Other Context 0 kid, Start (Container Context 1)]+ ++ [Start (Container Context 4)]+ ++ toASN1+ (DistinguishedName [(getObjectID DnCommonName, asn1CharacterString UTF8 "x")])+ []+ ++ [End (Container Context 4), End (Container Context 1)]+ ++ [Other Context 2 (B.pack [1]), End Sequence]+ )+ == Right (ExtAuthorityKeyId kid)+ where+ kid = B.pack [1, 2, 3]++-- RSASSA-PSS keys (with parameters) and other unknown keys are kept as+-- PubKeyUnknown.+property_unknown_pubkey :: Bool+property_unknown_pubkey =+ decode [] == Right (PubKeyUnknown pss key, [])+ && decode [Start Sequence, End Sequence] == Right (PubKeyUnknown pss key, [])+ where+ pss = [1, 2, 840, 113549, 1, 1, 10]+ key = B.pack [1, 2, 3]+ decode params =+ fromASN1+ ( [Start Sequence, Start Sequence, OID pss]+ ++ params+ ++ [End Sequence, BitString (toBitArray key 0), End Sequence]+ )+ :: Either String (PubKey, [ASN1])++property_ec_prime_roundtrip :: Bool+property_ec_prime_roundtrip = fromASN1 (toASN1 key []) == Right (key, [])+ where+ key =+ PubKeyEC+ PubKeyEC_Prime+ { pubkeyEC_pub = SerializedPoint (B.pack [4, 1, 2])+ , pubkeyEC_a = 3+ , pubkeyEC_b = 0x1234+ , pubkeyEC_prime = 0xfffffffffffffffffffffffffffffffeffffffffffffffff+ , pubkeyEC_generator = SerializedPoint (B.pack [4, 5, 6])+ , pubkeyEC_order = 0xffffffffffffffffffffffff99def836146bc9b1b4d22831+ , pubkeyEC_cofactor = 1+ , pubkeyEC_seed = 0x3045ae6fc8422f64ed579528d38120eae12196d5+ }++property_unique_ids :: Bool+property_unique_ids =+ decodeCert (toASN1 sampleCert [] ++ [Other Context 1 b, Other Context 2 b])+ == Right (sampleCert, [])+ && isLeft' (decodeCert (toASN1 sampleCert{certVersion = 3} []))+ where+ b = B.pack [0, 1]++-- Times with a zone offset are converted to UTC, and UTCTime is used+-- from 1950 through 2049.+property_validity_time :: Bool+property_validity_time =+ fmap (certValidity . fst) (decodeCert (map withOffset (toASN1 sampleCert [])))+ == Right (t', t')+ && map timeType (validity 1949) == [TimeGeneralized]+ && map timeType (validity 1950) == [TimeUTC]+ && map timeType (validity 2049) == [TimeUTC]+ && map timeType (validity 2050) == [TimeGeneralized]+ where+ (t, _) = certValidity sampleCert+ t' = timeAdd t (Hours (-9))+ withOffset (ASN1Time ty d _) = ASN1Time ty d (Just (TimezoneOffset 540))+ withOffset a = a+ validity y =+ take+ 1+ [ a+ | a@ASN1Time{} <-+ toASN1 sampleCert{certValidity = (year y, year y)} []+ ]+ year y = timeConvert (Date y January 1) :: DateTime+ timeType (ASN1Time ty _ _) = ty+ timeType _ = TimeUTC++property_crl_v1 :: Bool+property_crl_v1 =+ take 1 encoded /= [IntVal 0]+ && fromASN1 encoded == Right (crl, [])+ where+ t = timeConvert (Date 2020 January 1) :: DateTime+ crl =+ CRL+ 0+ (SignatureALG HashSHA256 PubKeyALG_RSA)+ (DistinguishedName [(getObjectID DnCommonName, asn1CharacterString UTF8 "x")])+ t+ Nothing+ []+ (Extensions Nothing)+ encoded = toASN1 crl []++-- RFC 5915: the private key octet string is as long as the order.+property_ec_privkey_length :: Bool+property_ec_privkey_length =+ [B.length o | OctetString o <- asn1] == [32]+ && fromASN1 asn1 == Right (key, [])+ where+ key = PrivKeyEC (PrivKeyEC_Named ECC.SEC_p256r1 1)+ asn1 = toASN1 key []++-- Explicit parameters name a curve only if the generator and the+-- cofactor match too.+property_ec_curve_name :: Bool+property_ec_curve_name =+ ecPubKeyCurveName (explicit g 1) == Just ECC.SEC_p256r1+ && ecPubKeyCurveName (explicit (ECC.pointMul curve 2 g) 1) == Nothing+ && ecPubKeyCurveName (explicit g 2) == Nothing+ where+ curve = ECC.getCurveByName ECC.SEC_p256r1+ cc = ECC.common_curve curve+ p = case curve of+ ECC.CurveFP (ECC.CurvePrime q _) -> q+ _ -> 0+ g = ECC.ecc_g cc+ point (ECC.Point x y) = SerializedPoint (B.cons 4 (i2ospOf_ 32 x <> i2ospOf_ 32 y))+ point ECC.PointO = SerializedPoint (B.singleton 0)+ explicit gen h =+ PubKeyEC_Prime+ { pubkeyEC_pub = point g+ , pubkeyEC_a = ECC.ecc_a cc+ , pubkeyEC_b = ECC.ecc_b cc+ , pubkeyEC_prime = p+ , pubkeyEC_generator = point gen+ , pubkeyEC_order = ECC.ecc_n cc+ , pubkeyEC_cofactor = h+ , pubkeyEC_seed = 0+ }++property_pss_default :: Bool+property_pss_default =+ fromASN1 asn1 == Right (SignatureALG HashSHA1 PubKeyALG_RSAPSS, [])+ && toASN1 (SignatureALG HashSHA1 PubKeyALG_RSAPSS) [] == asn1+ where+ asn1 =+ [ Start Sequence+ , OID [1, 2, 840, 113549, 1, 1, 10]+ , Start Sequence+ , End Sequence+ , End Sequence+ ]++-- The usual form (as written by OpenSSL), and points with reasons and a+-- cRLIssuer, whose name only is kept, or without a name, which are dropped.+property_crl_dp_der :: Bool+property_crl_dp_der =+ extensionDecode (ExtensionRaw [2, 5, 29, 31] False der)+ == Just+ (Right (ExtCrlDistributionPoints [DistributionPointFullName [AltNameURI url]]))+ && extEncodeBs+ (ExtCrlDistributionPoints [DistributionPointFullName [AltNameURI url]])+ == der+ && extDecode+ ( [Start Sequence]+ ++ dp (uriName ++ [Other Context 1 (B.pack [6, 0x40])] ++ issuer)+ ++ dp issuer+ ++ [End Sequence]+ )+ == Right (ExtCrlDistributionPoints [DistributionPointFullName [AltNameURI url]])+ where+ url = "http://crl.example.com/ca.crl"+ der =+ B.pack+ ( [0x30, 0x25, 0x30, 0x23, 0xa0, 0x21, 0xa0, 0x1f, 0x86, 0x1d]+ ++ map (fromIntegral . fromEnum) url+ )+ uriName =+ [ Start (Container Context 0)+ , Start (Container Context 0)+ , Other Context 6 (B.pack (map (fromIntegral . fromEnum) url))+ , End (Container Context 0)+ , End (Container Context 0)+ ]+ issuer =+ [ Start (Container Context 2)+ , Other Context 2 (B.pack [0x61])+ , End (Container Context 2)+ ]+ dp xs = [Start Sequence] ++ xs ++ [End Sequence]+ property_extension_id :: (Show e, Eq e, Extension e) => e -> Bool property_extension_id e = case extDecode (extEncode e) of Left err -> error err@@ -598,6 +949,18 @@ | v == e -> True | otherwise -> error ("expected " ++ show e ++ " got: " ++ show v) +-- Per-family AlgorithmIdentifier parameters contract:+-- ECDSA (RFC 5758 3.2, RFC 3279 2.2.3) and DSA (RFC 5758 3.1, RFC 3279+-- 2.2.2) omit the parameters field; RSA PKCS#1 v1.5 encodes an ASN.1+-- NULL (RFC 3279 2.2.1); EdDSA omits the field (RFC 8410 3).+property_sig_alg_parameters :: SignatureALG -> Bool+property_sig_alg_parameters alg@(SignatureALG _ pub)+ | pub == PubKeyALG_EC || pub == PubKeyALG_DSA = Null `notElem` toASN1 alg []+ | pub == PubKeyALG_RSA = Null `elem` toASN1 alg []+property_sig_alg_parameters alg@(SignatureALG_IntrinsicHash _) =+ Null `notElem` toASN1 alg []+property_sig_alg_parameters _ = True+ main = defaultMain $ testGroup@@ -619,6 +982,10 @@ "subject-alt-name" (property_extension_id :: ExtSubjectAltName -> Bool) , testProperty+ "crl-distribution-points"+ (property_extension_id :: ExtCrlDistributionPoints -> Bool)+ , testProperty "crl-distribution-points-der" property_crl_dp_der+ , testProperty "name-constraints" (property_extension_id :: ExtNameConstraints -> Bool) , testProperty "name-constraints DER" property_name_constraints_der@@ -629,6 +996,31 @@ , testProperty "extensions" property_malformed_extensions , testProperty "SAN skips unknown names" property_san_skips_unknown , testProperty "lazy decode error" property_lazy_decode_error+ , testProperty "signed object" property_signed_strict+ , testProperty "duplicate extensions" property_duplicate_extensions+ , testProperty "RSA key trailing data" property_rsa_pubkey_trailing+ , testProperty "PSS hash" property_pss_hash+ , testProperty "private key" property_privkey_malformed+ ]+ , testGroup+ "interoperability"+ [ testProperty "KeyUsage DER" property_key_usage_der+ , testProperty "BasicConstraints without cA" property_basic_constraints_no_ca+ , testProperty "AKI with issuer and serial" property_aki_issuer_serial+ , testProperty "unknown public key" property_unknown_pubkey+ , testProperty "EC explicit parameters" property_ec_prime_roundtrip+ , testProperty "unique IDs" property_unique_ids+ , testProperty "validity time" property_validity_time+ , testProperty "v1 CRL" property_crl_v1+ , testProperty "PSS default parameters" property_pss_default+ , testProperty "EC private key length" property_ec_privkey_length+ , testProperty "EC curve name" property_ec_curve_name+ ]+ , testGroup+ "signature-alg-parameters"+ [ testProperty+ "per-family"+ property_sig_alg_parameters ] , testProperty "extensions"
crypton-x509.cabal view
@@ -1,6 +1,6 @@ cabal-version: >=1.10 name: crypton-x509-version: 1.10.2+version: 1.10.3 license: BSD3 license-file: LICENSE copyright: Vincent Hanquez <vincent@snarc.org>@@ -17,7 +17,7 @@ source-repository head type: git location: https://github.com/kazu-yamamoto/crypton-certificate- subdir: x509+ subdir: crypton-x509 library exposed-modules: