packages feed

crypton-x509-validation 1.6.14 → 1.11.0

raw patch · 8 files changed

Files

+ ChangeLog.md view
@@ -0,0 +1,83 @@+# ChangeLog for crypton-x509-validation++## 1.11.0++The constructors of `ValidationChecks` and `ValidationHooks` are hidden;+use `defaultChecks` and `defaultHooks` with record update syntax.+RSA-PSS signatures are verified with their own parameters and the+restrictions of RSASSA-PSS keys, and SHA-3 signatures are supported.++* Hide the constructors of ValidationChecks and ValidationHooks+  [#51](https://github.com/kazu-yamamoto/crypton-certificate/pull/51)+* Add checkRejectSHA1 and OtherReason+  [#52](https://github.com/kazu-yamamoto/crypton-certificate/pull/52)+* Keep RSA-PSS parameters+  [#53](https://github.com/kazu-yamamoto/crypton-certificate/pull/53)+* Keep multi-valued RDNs+  [#54](https://github.com/kazu-yamamoto/crypton-certificate/pull/54)+* Keep all GeneralName forms+  [#57](https://github.com/kazu-yamamoto/crypton-certificate/pull/57)+* Support RSASSA-PSS keys+  [#61](https://github.com/kazu-yamamoto/crypton-certificate/pull/61)+* Support SHA-3 signature algorithms+  [#62](https://github.com/kazu-yamamoto/crypton-certificate/pull/62)++## 1.10.3++MD2 and MD5 signatures are rejected, and certification paths are built+with backtracking.++* Harden certificate validation+  [#44](https://github.com/kazu-yamamoto/crypton-certificate/pull/44)+* 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++* Fix host name validation with iPAddress SANs: an IP address is+  matched only against iPAddress SANs and the CN is not used if the+  SubjectAltName extension is present, even without dNSName.+* An IP address is no longer matched against the CN of a certificate+  without SubjectAltName.++## 1.10.1++* Fix name constraint bypasses: constraints are accumulated per RFC+  5280, apply to the leaf even if self-issued and to the CN used as a+  host name, dNSName matching is case-insensitive, and iPAddress,+  rfc822Name, URI and directoryName constraints are enforced.+* Undecodable NameConstraints, BasicConstraints, KeyUsage,+  ExtendedKeyUsage and SubjectAltName extensions fail validation+  instead of being ignored.+* Reject degenerate DSA parameters and oversized RSA keys before+  verifying signatures.+* Limit the chain depth to 20 CA certificates.++## 1.10.0++* Verify ML-DSA signatures+  [#35](https://github.com/kazu-yamamoto/crypton-certificate/pull/35)+* Follow the breaking change in `crypton-x509` 1.10.0+  [#35](https://github.com/kazu-yamamoto/crypton-certificate/pull/35)++## 1.9.1++* Implementing the X509 name constrains extension.+  [#30](https://github.com/kazu-yamamoto/crypton-certificate/pull/30)++## 1.9.0++* Using "ram" instead of "memory"+  [#29](https://github.com/kazu-yamamoto/crypton-certificate/pull/29)++## 1.8.0++* Depend on package `time-hourglass`, rather than `hourglass`. Date and+  time-related types and classes are now those from the former package.+  [#18](https://github.com/kazu-yamamoto/crypton-certificate/pull/18)+* Depend on package `crypton-asn1-types >= 0.4.1` rather than `asn1-types`.+  ASN.1-related types and classes are now those from the former package.
Data/X509/Validation.hs view
@@ -20,8 +20,24 @@     SignatureFailure (..),      -- * Validation configuration types-    ValidationChecks (..),-    ValidationHooks (..),++    -- the constructors are hidden so that fields can be added+    ValidationChecks,+    checkTimeValidity,+    checkAtTime,+    checkStrictOrdering,+    checkCAConstraints,+    checkExhaustive,+    checkLeafV3,+    checkLeafKeyUsage,+    checkLeafKeyPurpose,+    checkFQHN,+    checkRejectSHA1,+    ValidationHooks,+    hookMatchSubjectIssuer,+    hookValidateTime,+    hookValidateName,+    hookFilterReason,     defaultChecks,     defaultHooks, @@ -38,14 +54,17 @@     module Data.X509.Validation.Signature, ) where +import Control.Applicative ((<|>)) import Control.Monad (when)+import Control.Monad.State.Strict (State, evalState, get, put) import Data.ASN1.Types import Data.Bits-import Data.ByteString (unpack)+import Data.ByteString (ByteString, unpack)+import qualified Data.ByteString as B import Data.Char (toLower) import Data.Default import Data.Hourglass-import Data.IP (IPv4, IPv6, toIPv4, toIPv6)+import Data.IP (IPv4, IPv6, fromIPv4, fromIPv6b, toIPv4, toIPv6) import Data.List import Data.Maybe import Data.Word (Word8)@@ -53,10 +72,11 @@ import Data.X509.CertificateStore import Data.X509.Validation.Cache import Data.X509.Validation.Fingerprint+import Data.X509.Validation.Internal (safeCharacterToString) import Data.X509.Validation.Signature import Data.X509.Validation.Types-import System.Hourglass import Text.Read (readMaybe)+import Time.System  -- | Possible reason of certificate and chain failure. --@@ -65,7 +85,7 @@ -- instead. data FailedReason     = -- | certificate contains an unknown critical extension-      UnknownCriticalExtension+      UnknownCriticalExtension OID     | -- | validity ends before checking time       Expired     | -- | validity starts after checking time@@ -100,12 +120,14 @@       CacheSaysNo String     | -- | signature failed       InvalidSignature SignatureFailure+    | -- | a reason given by a hook, e.g. a revocation check+      OtherReason String     deriving (Show, Eq)  -- | A set of checks to activate or parametrize to perform on certificates. ----- It's recommended to use 'defaultChecks' to create the structure,--- to better cope with future changes or expansion of the structure.+-- Values are made by updating 'defaultChecks', e.g.+-- @defaultChecks{checkFQHN = False}@. data ValidationChecks = ValidationChecks     { checkTimeValidity :: Bool     -- ^ check time validity of every certificate in the chain.@@ -145,11 +167,16 @@     , checkFQHN :: Bool     -- ^ Check the top certificate names matching the fully qualified hostname (FQHN).     -- it's not recommended to turn this check off, if no other name checks are performed.+    , checkRejectSHA1 :: Bool+    -- ^ Reject certificates signed with SHA-1.  The signatures of trust+    -- anchors are not checked.  MD2 and MD5 are always rejected.     }     deriving (Show, Eq)  -- | A set of hooks to manipulate the way the verification works. --+-- Values are made by updating 'defaultHooks'.+-- -- BEWARE, it's easy to change behavior leading to compromised security. data ValidationHooks = ValidationHooks     { hookMatchSubjectIssuer :: DistinguishedName -> Certificate -> Bool@@ -184,6 +211,7 @@         , checkLeafKeyUsage = []         , checkLeafKeyPurpose = []         , checkFQHN = True+        , checkRejectSHA1 = False         }  instance Default ValidationChecks where@@ -272,47 +300,114 @@     -- ^ the return failed reasons (empty list is no failure) validatePure _ _ _ _ _ (CertificateChain []) = [EmptyChain] validatePure validationTime hooks checks store (fqhn, _) (CertificateChain (top : rchain)) =-    hookFilterReason hooks (doLeafChecks |> doCheckChain 0 top rchain)+    hookFilterReason+        hooks+        (doLeafChecks |> chainFailures |> maybe [] doCheckNameConst mpath)   where+    (chainFailures, mpath) = evalState (doCheckChain 0 top rchain) maxSignatureChecks++    isExhaustive :: Bool     isExhaustive = checkExhaustive checks++    (|>) :: [FailedReason] -> [FailedReason] -> [FailedReason]     a |> b = exhaustive isExhaustive a b -    doLeafChecks = doNameCheck top ++ doV3Check topCert ++ doKeyUsageCheck topCert+    doLeafChecks :: [FailedReason]+    doLeafChecks =+        doNameCheck top+            ++ doV3Check topCert+            ++ doKeyUsageCheck topCert       where         topCert = getCertificate top +    -- Failures of the first path that succeeds, or else of the first+    -- path tried, with the certificates from the current one to the trust+    -- anchor if the path reaches one.     doCheckChain-        :: Int -> SignedCertificate -> [SignedCertificate] -> [FailedReason]-    doCheckChain level current chain =-        doCheckCertificate (getCertificate current)-            -- check if we have a trusted certificate in the store belonging to this issuer.-            |> ( case findCertificate (certIssuerDN cert) store of-                    Just trustedSignedCert -> checkSignature current trustedSignedCert-                    Nothing-                        | isSelfSigned cert -> [SelfSigned] |> checkSignature current current-                        | null chain -> [UnknownCA]-                        | otherwise ->-                            case findIssuer (certIssuerDN cert) chain of-                                Nothing -> [UnknownCA]-                                Just (issuer, remaining) ->-                                    checkCA level (getCertificate issuer)-                                        |> checkSignature current issuer-                                        |> doCheckChain (level + 1) issuer remaining-               )+        :: Int+        -> SignedCertificate+        -> [SignedCertificate]+        -> State Int ([FailedReason], Maybe [SignedCertificate])+    doCheckChain level current chain+        | level > maxChainDepth = return ([AuthorityTooDeep], Nothing)+        | otherwise =+            fmap (fmap (current :))+                <$> (doCheckCertificate cert `andThen` issuerChecks)       where         cert = getCertificate current-    -- in a strict ordering check the next certificate has to be the issuer.-    -- otherwise we dynamically reorder the chain to have the necessary certificate-    findIssuer issuerDN chain-        | checkStrictOrdering checks =-            case chain of-                [] -> error "not possible"-                (c : cs)-                    | matchSubjectIdentifier issuerDN (getCertificate c) -> Just (c, cs)-                    | otherwise -> Nothing+        issuerDN = certIssuerDN cert+        anchors = findCertificates issuerDN store+        issuerChecks+            | null anchors && isSelfSigned cert = do+                r <- checkSignatureM current current+                return ([SelfSigned] |> r, Nothing)+            | otherwise =+                firstSuccess $+                    map anchorCheck anchors+                        ++ [chainCheck i r | (i, r) <- findIssuers issuerDN chain]+        anchorCheck anchor+            -- an anchor that is not a CA may only be the certificate itself+            | checkCAConstraints checks+                && anchor /= current+                && notCA (getCertificate anchor) =+                return ([NotAnAuthority], Nothing)+            | otherwise = do+                r <- checkSignatureM current anchor+                return (r, Just [anchor])+        chainCheck issuer remaining = do+            r <- checkSignatureM current issuer+            (checkCA level (getCertificate issuer) |> r)+                `andThen` doCheckChain (level + 1) issuer remaining++    -- Runs the next step unless the failures stop the validation.+    andThen+        :: [FailedReason]+        -> State Int ([FailedReason], Maybe p)+        -> State Int ([FailedReason], Maybe p)+    andThen fs next+        | null fs || isExhaustive = (\(fs', p) -> (fs ++ fs', p)) <$> next+        | otherwise = return (fs, Nothing)++    firstSuccess+        :: [State Int ([FailedReason], Maybe p)]+        -> State Int ([FailedReason], Maybe p)+    firstSuccess = go Nothing+      where+        go failed [] = return $ fromMaybe ([UnknownCA], Nothing) failed+        go failed (m : ms) = do+            r@(fs, _) <- m+            if null fs then return r else go (failed <|> Just r) ms++    -- A signature check spends the budget, which bounds path building.+    checkSignatureM+        :: SignedCertificate -> SignedCertificate -> State Int [FailedReason]+    checkSignatureM signedCert signingCert = do+        budget <- get+        if budget <= 0+            then return [UnknownCA]+            else do+                put (budget - 1)+                return $ checkSignature signedCert signingCert++    -- Issuer candidates in the chain with the remaining certificates.  In+    -- a strict ordering check the next certificate has to be the issuer.+    findIssuers+        :: DistinguishedName+        -> [SignedCertificate]+        -> [(SignedCertificate, [SignedCertificate])]+    findIssuers issuerDN chain+        | checkStrictOrdering checks = case chain of+            c : cs | matches c -> [(c, cs)]+            _ -> []         | otherwise =-            (\x -> (x, filter (/= x) chain))-                `fmap` find (matchSubjectIdentifier issuerDN . getCertificate) chain+            [ (c, before ++ after)+            | (before, c : after) <- zip (inits chain) (tails chain)+            , matches c+            ]+      where+        matches = matchSubjectIdentifier issuerDN . getCertificate++    matchSubjectIdentifier :: DistinguishedName -> Certificate -> Bool     matchSubjectIdentifier = hookMatchSubjectIssuer hooks      -- we check here that the certificate is allowed to be a certificate@@ -330,11 +425,13 @@                 ++ (if allowedDepth then [] else [AuthorityTooDeep])       where         extensions = certExtensions cert-        allowedSign = case extensionGet extensions of-            Just (ExtKeyUsage flags) -> KeyUsage_keyCertSign `elem` flags+        -- an extension that cannot be decoded is not treated as absent+        allowedSign = case extensionGetE extensions of+            Just (Right (ExtKeyUsage flags)) -> KeyUsage_keyCertSign `elem` flags+            Just (Left _) -> False             Nothing -> True-        (allowedCA, pathLen) = case extensionGet extensions of-            Just (ExtBasicConstraints True pl) -> (True, pl)+        (allowedCA, pathLen) = case extensionGetE extensions of+            Just (Right (ExtBasicConstraints True pl)) -> (True, pl)             _ -> (False, Nothing)         allowedDepth = case pathLen of             Nothing -> True@@ -342,16 +439,19 @@                 | fromIntegral pl >= level -> True                 | otherwise -> False +    doNameCheck :: SignedCertificate -> [FailedReason]     doNameCheck cert         | not (checkFQHN checks) = []         | otherwise = (hookValidateName hooks) fqhn (getCertificate cert) +    doV3Check :: Certificate -> [FailedReason]     doV3Check cert         | checkLeafV3 checks = case certVersion cert of             2 {- confusingly it means X509.V3 -} -> []             _ -> [LeafNotV3]         | otherwise = [] +    doKeyUsageCheck :: Certificate -> [FailedReason]     doKeyUsageCheck cert =         compareListIfExistAndNotNull             mflags@@ -362,35 +462,122 @@                 (checkLeafKeyPurpose checks)                 LeafKeyPurposeNotAllowed       where-        mflags = case extensionGet $ certExtensions cert of-            Just (ExtKeyUsage keyflags) -> Just keyflags+        mflags = case extensionGetE $ certExtensions cert of+            Just (Right (ExtKeyUsage keyflags)) -> Just (Right keyflags)+            Just (Left e) -> Just (Left e)             Nothing -> Nothing-        mpurposes = case extensionGet $ certExtensions cert of-            Just (ExtExtendedKeyUsage keyPurposes) -> Just keyPurposes+        mpurposes = case extensionGetE $ certExtensions cert of+            -- anyExtendedKeyUsage does not restrict the purposes+            Just (Right (ExtExtendedKeyUsage keyPurposes))+                | KeyUsagePurpose_Unknown [2, 5, 29, 37, 0] `elem` keyPurposes -> Nothing+                | otherwise -> Just (Right keyPurposes)+            Just (Left e) -> Just (Left e)             Nothing -> Nothing         -- compare a list of things to an expected list. the expected list         -- need to be a subset of the list (if not Nothing), and is not will-        -- return [err]+        -- return [err]. An undecodable extension always fails.         compareListIfExistAndNotNull Nothing _ _ = []-        compareListIfExistAndNotNull (Just list) expected err+        compareListIfExistAndNotNull (Just (Left _)) _ err = [err]+        compareListIfExistAndNotNull (Just (Right list)) expected err             | null expected = []             | intersect expected list == expected = []             | otherwise = [err] +    doCheckCertificate :: Certificate -> [FailedReason]     doCheckCertificate cert =         exhaustiveList             (checkExhaustive checks)             [ (checkTimeValidity checks, hookValidateTime hooks validationTime cert)+            , (True, doCriticalExtensionSweep cert)             ]-    isSelfSigned :: Certificate -> Bool-    isSelfSigned cert = certSubjectDN cert == certIssuerDN cert-     -- check signature of 'signedCert' against the 'signingCert'-    checkSignature signedCert signingCert =-        case verifySignedSignature signedCert (certPubKey $ getCertificate signingCert) of-            SignaturePass -> []-            SignatureFailed r -> [InvalidSignature r]+    -- The signature algorithm must also match the signed one in the TBS.+    checkSignature+        :: SignedCertificate -> SignedCertificate -> [FailedReason]+    checkSignature signedCert signingCert+        | signedAlg (getSigned signedCert) /= certSignatureAlg (getCertificate signedCert) =+            [InvalidSignature SignatureInvalid]+        | checkRejectSHA1 checks && isSHA1 (signedAlg (getSigned signedCert)) =+            [InvalidSignature SignatureUnimplemented]+        | otherwise =+            case verifySignedSignature signedCert (certPubKey $ getCertificate signingCert) of+                SignaturePass -> []+                SignatureFailed r -> [InvalidSignature r] +    -- The path runs from the leaf to the trust anchor.+    doCheckNameConst :: [SignedCertificate] -> [FailedReason]+    doCheckNameConst path = case reverse path of+        anchor : rest ->+            checkNameConstraints $+                getNameConstSpec (getCertificate anchor) False+                    : zipWith spec [length rest - 1, length rest - 2 ..] rest+        [] -> []+      where+        -- the level counts from the leaf+        spec level c = getNameConstSpec (getCertificate c) (level == 0 && checkFQHN checks)++isSHA1 :: SignatureALG -> Bool+isSHA1 (SignatureALG HashSHA1 _) = True+isSHA1 alg = maybe False ((== HashSHA1) . pssHash) $ signatureALGPSSParams alg++-- | Whether BasicConstraints says the certificate is not a CA.+notCA :: Certificate -> Bool+notCA cert = case extensionGetE (certExtensions cert) of+    Just (Right (ExtBasicConstraints False _)) -> True+    Just (Left _) -> True+    _ -> False++isSelfSigned :: Certificate -> Bool+isSelfSigned cert = certSubjectDN cert == certIssuerDN cert++-- | The maximum number of CA certificates followed from the leaf.+maxChainDepth :: Int+maxChainDepth = 20++-- | The maximum number of signatures checked while building paths.+maxSignatureChecks :: Int+maxSignatureChecks = 100++data NameConstSpec = NameConstSpec+    { ncNames :: Either String [AltName]+    -- ^ names subject to name constraints+    , ncExt :: Either String (Maybe ExtNameConstraints)+    , ncSelfIssued :: Bool+    }++-- | The second argument tells whether the CN is used as a host name.+getNameConstSpec :: Certificate -> Bool -> NameConstSpec+getNameConstSpec cert useCN =+    NameConstSpec+        { ncNames = names+        , ncExt = maybe (Right Nothing) (fmap Just) $ extensionGetE exts+        , ncSelfIssued = isSelfSigned cert+        }+  where+    exts = certExtensions cert+    subjDN = certSubjectDN cert+    subj = [AltNameDN subjDN | not (null (getDistinguishedElements subjDN))]+    -- RFC 5280: without SAN, emailAddress in the subject is an rfc822Name+    emails =+        [ AltNameRFC822 e+        | (oid, v) <- getDistinguishedElements subjDN+        , oid == [1, 2, 840, 113549, 1, 9, 1]+        , Just e <- [safeCharacterToString v]+        ]+    cn+        | useCN = case getNames cert of+            Right (Just name, Nothing) -> [maybe (AltNameDNS name) ipToAltName (parseIPAddress name)]+            _ -> []+        | otherwise = []+    names = case extensionGetE exts of+        Nothing -> Right (subj ++ emails ++ cn)+        Just (Right (ExtSubjectAltName alts)) -> Right (subj ++ alts ++ cn)+        Just (Left e) -> Left e++ipToAltName :: IPAddress -> AltName+ipToAltName (IPv4Address ip) = AltNameIP $ B.pack $ map fromIntegral $ fromIPv4 ip+ipToAltName (IPv6Address ip) = AltNameIP $ B.pack $ map fromIntegral $ fromIPv6b ip+ -- | Validate that the current time is between validity bounds validateTime :: DateTime -> Certificate -> [FailedReason] validateTime currentTime cert@@ -400,44 +587,39 @@   where     (before, after) = certValidity cert -getNames :: Certificate -> (Maybe String, [String])-getNames cert = (commonName >>= asn1CharacterToString, altNames)+-- | The commonName and the SAN entries ('Nothing' without the extension).+-- 'Left' if the SAN extension is present but cannot be decoded.+getNames :: Certificate -> Either String (Maybe String, Maybe [AltName])+getNames cert = case extensionGetE $ certExtensions cert of+    Just (Left e) -> Left e+    Just (Right (ExtSubjectAltName names)) -> Right (commonName, Just names)+    Nothing -> Right (commonName, Nothing)   where-    commonName = getDnElement DnCommonName $ certSubjectDN cert-    altNames = maybe [] toAltName $ extensionGet $ certExtensions cert-    toAltName (ExtSubjectAltName names) = catMaybes $ map unAltName names-      where-        unAltName (AltNameDNS s) = Just s-        unAltName _ = Nothing+    commonName = getDnElement DnCommonName (certSubjectDN cert) >>= safeCharacterToString  data IPAddress     = IPv4Address IPv4     | IPv6Address IPv6     deriving (Eq) -getIPs :: Certificate -> [IPAddress]-getIPs cert = fromMaybe [] (toAltName <$> (extensionGet $ certExtensions cert))+toIPAddress :: ByteString -> Maybe IPAddress+toIPAddress s = case unpack s of+    [a, b, c, d] -> Just $ IPv4Address $ toIPv4 $ fmap fromIntegral [a, b, c, d]+    [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p] ->+        Just $+            IPv6Address $+                toIPv6+                    [ fuse a b+                    , fuse c d+                    , fuse e f+                    , fuse g h+                    , fuse i j+                    , fuse k l+                    , fuse m n+                    , fuse o p+                    ]+    _ -> Nothing   where-    toAltName (ExtSubjectAltName names) = catMaybes $ map unAltName names--    unAltName (AltNameIP s) = case unpack s of-        [a, b, c, d] -> Just $ IPv4Address $ toIPv4 $ fmap fromIntegral [a, b, c, d]-        [a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p] ->-            Just $-                IPv6Address $-                    toIPv6-                        [ fuse a b-                        , fuse c d-                        , fuse e f-                        , fuse g h-                        , fuse i j-                        , fuse k l-                        , fuse m n-                        , fuse o p-                        ]-        _ -> Nothing-    unAltName _ = Nothing-     fuse :: Word8 -> Word8 -> Int     fuse a b = shiftL (fromIntegral a) 8 .|. (fromIntegral b) @@ -447,29 +629,34 @@ parseIPAddress _ = Nothing  -- | Validate that the fqhn is matched by at least one name in the certificate.--- If the subjectAltname extension is present, then the certificate commonName--- is ignored, and only the DNS names and IP Addresses, if any, in the--- subjectAltName are considered.  Otherwise, the commonName from the subjectDN--- is used.+-- An IP address is matched only against the iPAddress entries of the+-- subjectAltName.  A host name is matched against the dNSName entries if+-- the subjectAltName extension is present, even if it has no dNSName.+-- Otherwise, the commonName from the subjectDN is used. --+-- If the subjectAltName extension cannot be decoded, the name never matches.+-- -- Note that DNS names in the subjectAltName are in IDNA A-label form. If the -- destination hostname is a UTF-8 name, it must be provided to the TLS context -- in (non-transitional) IDNA2008 A-label form. validateCertificateName :: HostName -> Certificate -> [FailedReason]-validateCertificateName fqhn cert-    | not $ null altNames =-        case parseIPAddress fqhn of-            Nothing -> findMatch [] $ map matchDomain altNames-            Just ip ->-                if elem ip (getIPs cert)-                    then []-                    else [NameMismatch fqhn]-    | otherwise =-        case commonName of+validateCertificateName fqhn cert = case getNames cert of+    Left _ -> [NameMismatch fqhn]+    Right names -> validateNames fqhn names++validateNames+    :: HostName -> (Maybe String, Maybe [AltName]) -> [FailedReason]+validateNames fqhn (commonName, mAltNames) = case parseIPAddress fqhn of+    Just ip+        | ip `elem` [a | AltNameIP b <- altNames, Just a <- [toIPAddress b]] -> []+        | otherwise -> [NameMismatch fqhn]+    Nothing -> case mAltNames of+        Just _ -> findMatch [] $ [matchDomain n | AltNameDNS n <- altNames]+        Nothing -> case commonName of             Nothing -> [NoCommonName]             Just cn -> findMatch [] $ [matchDomain cn]   where-    (commonName, altNames) = getNames cert+    altNames = fromMaybe [] mAltNames      findMatch :: [FailedReason] -> [[FailedReason]] -> [FailedReason]     findMatch _ [] = [NameMismatch fqhn]@@ -480,7 +667,7 @@     matchDomain name = case splitDot name of         l             | any (== "") l -> [InvalidName name]-            | head l == "*" -> wildcardMatch (drop 1 l)+            | take 1 l == ["*"] -> wildcardMatch (drop 1 l)             | l == splitDot fqhn -> [] -- success: we got a match             | otherwise -> [NameMismatch fqhn] @@ -495,9 +682,10 @@     --     -- e.g. *.*.server.com will try to litteraly match the '*' subdomain of server.com     ---    -- Also '*' is not accepted as a valid wildcard+    -- Also '*' and a wildcard for a single label such as '*.com' are not+    -- accepted as valid wildcards     wildcardMatch l-        | null l = [InvalidWildcard] -- '*' is always invalid+        | length l < 2 = [InvalidWildcard]         | l == drop 1 (splitDot fqhn) = [] -- success: we got a match         | otherwise = [NameMismatch fqhn] @@ -509,8 +697,11 @@  -- | return true if the 'subject' certificate's issuer match -- the 'issuer' certificate's subject+-- | Names are compared in their canonical form (RFC 5280 7.1). matchSI :: DistinguishedName -> Certificate -> Bool-matchSI issuerDN issuer = certSubjectDN issuer == issuerDN+matchSI issuerDN issuer =+    canonicalDistinguishedName (certSubjectDN issuer)+        == canonicalDistinguishedName issuerDN  exhaustive :: Bool -> [FailedReason] -> [FailedReason] -> [FailedReason] exhaustive isExhaustive l1 l2@@ -523,3 +714,175 @@ exhaustiveList isExhaustive ((performCheck, c) : cs)     | performCheck = exhaustive isExhaustive c (exhaustiveList isExhaustive cs)     | otherwise = exhaustiveList isExhaustive cs++-- | Name constraints accumulated along the chain (RFC 5280 6.1):+-- a name must be in a permitted subtree of every level that has one+-- and must not be in any excluded subtree.+data NameConstState = NameConstState [[GeneralSubtree]] [GeneralSubtree]++-- | The first element is the trust anchor and the last is the leaf.+checkNameConstraints :: [NameConstSpec] -> [FailedReason]+checkNameConstraints [] = []+checkNameConstraints (anchor : specs0) =+    either id (\st -> loop st specs0) $ addNameConst (NameConstState [] []) anchor+  where+    loop _ [] = []+    loop st (spec : specs) =+        check ++ case specs of+            [] -> []+            _ -> either id (\st' -> loop st' specs) $ addNameConst st spec+      where+        -- self-issued intermediates are exempt but the leaf is not+        check+            | ncSelfIssued spec && not (null specs) = []+            | otherwise = validateNames' st (ncNames spec)++addNameConst+    :: NameConstState -> NameConstSpec -> Either [FailedReason] NameConstState+addNameConst st@(NameConstState permitted excluded) spec = case ncExt spec of+    Left e -> Left [InvalidName $ "NameConstraints: " ++ e]+    Right Nothing -> Right st+    Right (Just (ExtNameConstraints p e)) ->+        Right $ NameConstState ([p | not (null p)] ++ permitted) (e ++ excluded)++validateNames' :: NameConstState -> Either String [AltName] -> [FailedReason]+validateNames' (NameConstState [] []) _ = []+validateNames' _ (Left e) = [InvalidName $ "SubjectAltName: " ++ e]+validateNames' (NameConstState permitted excluded) (Right altNames) =+    concatMap inc altNames ++ concatMap exc altNames+  where+    inc a+        | all (nsMatch a) permitted = []+        | otherwise = [InvalidName $ show a]+    exc a+        | nsNotMatch a excluded = []+        | otherwise = [InvalidName $ show a]++data NameMatch = NotApplicable | Matched | NotMatched | Unsupported+    deriving (Eq)++-- | A permitted subtree list is satisfied if the name is in one of them+-- or if none of them is of the same type as the name.+nsMatch :: AltName -> [GeneralSubtree] -> Bool+nsMatch a gs = any (== Matched) rs || all (== NotApplicable) rs+  where+    rs = map (matchSubtree False a) gs++nsNotMatch :: AltName -> [GeneralSubtree] -> Bool+nsNotMatch a = all ((`elem` [NotApplicable, NotMatched]) . matchSubtree True a)++-- | The first argument tells whether the subtree is an excluded one.+-- Unsupported forms count as matched when excluded and as not matched+-- when permitted.+matchSubtree :: Bool -> AltName -> GeneralSubtree -> NameMatch+matchSubtree isExcluded name (GeneralSubtree base _ _) = case (name, base) of+    (AltNameDNS n, AltNameDNS c) ->+        toMatch $ dnsInSubtree n c || (isExcluded && wildcardCovers n c)+    (AltNameDN n, AltNameDN c) -> toMatch $ dnInSubtree n c+    (AltNameIP n, AltNameIP c) -> ipInSubtree n c+    (AltNameRFC822 n, AltNameRFC822 c) -> maybe Unsupported toMatch $ emailInSubtree n c+    (AltNameURI n, AltNameURI c) -> maybe Unsupported (toMatch . (`hostInSubtree` c)) $ uriHost n+    (AltNameXMPP _, AltNameXMPP _) -> Unsupported+    (AltNameDNSSRV _, AltNameDNSSRV _) -> Unsupported+    (AltNameOther o1 _, AltNameOther o2 _)+        | o1 == o2 -> Unsupported+    (AltNameX400 _, AltNameX400 _) -> Unsupported+    (AltNameEDIParty _, AltNameEDIParty _) -> Unsupported+    (AltNameRegisteredID _, AltNameRegisteredID _) -> Unsupported+    _ -> NotApplicable+  where+    toMatch b = if b then Matched else NotMatched++-- | "example.com" covers itself and its subdomains, ".example.com" only+-- its subdomains.  Compared case-insensitively.+dnsInSubtree :: String -> String -> Bool+dnsInSubtree n c+    | null c' = True+    | "." `isPrefixOf` c' = c' `isSuffixOf` n'+    | otherwise = n' == c' || ('.' : c') `isSuffixOf` n'+  where+    n' = map toLower n+    c' = map toLower c++-- | Whether a wildcard name such as "*.example.com" may stand for a name+-- in the subtree, e.g. "www.example.com".+wildcardCovers :: String -> String -> Bool+wildcardCovers n c = case stripPrefix "*." (map toLower n) of+    Just rest ->+        let c' = map toLower c+            label = take (length c' - length rest - 1) c'+         in not (null label)+                && '.' `notElem` label+                && ('.' : rest) `isSuffixOf` c'+    Nothing -> False++hostInSubtree :: String -> String -> Bool+hostInSubtree h c+    | "." `isPrefixOf` c' = c' `isSuffixOf` h'+    | otherwise = h' == c'+  where+    h' = map toLower h+    c' = map toLower c++-- | "user@host" matches exactly, "host" matches all mailboxes on the host+-- and ".example.com" all mailboxes on its subdomains.+emailInSubtree :: String -> String -> Maybe Bool+emailInSubtree n c = case breakAt n of+    Just (local, host) -> Just $ case breakAt c of+        Just (cLocal, cHost) -> local == cLocal && map toLower host == map toLower cHost+        Nothing -> hostInSubtree host c+    Nothing -> Nothing+  where+    breakAt x = case break (== '@') (reverse x) of+        (rhost, '@' : rlocal) -> Just (reverse rlocal, reverse rhost)+        _ -> Nothing++-- | The host of a URI with an authority; 'Nothing' for IP literals.+uriHost :: String -> Maybe String+uriHost uri = case break (== ':') uri of+    (_, ':' : '/' : '/' : rest) ->+        let authority = takeWhile (`notElem` ("/?#" :: String)) rest+            hostport = reverse $ takeWhile (/= '@') $ reverse authority+            host = takeWhile (/= ':') hostport+         in if null host || "[" `isPrefixOf` hostport || isJust (parseIPAddress host)+                then Nothing+                else Just host+    _ -> Nothing++-- | The subtree is a prefix of the name, comparing RDNs in the canonical+-- form.+dnInSubtree :: DistinguishedName -> DistinguishedName -> Bool+dnInSubtree n c = canon c `isPrefixOf` canon n+  where+    canon = getRDNs . canonicalDistinguishedName++-- | An IPv4 or IPv6 address against an address with a mask.+ipInSubtree :: ByteString -> ByteString -> NameMatch+ipInSubtree n c+    | B.length c /= 8 && B.length c /= 32 = Unsupported+    | B.length n /= 4 && B.length n /= 16 = Unsupported+    | 2 * B.length n /= B.length c = NotMatched+    | otherwise =+        if and+            ( zipWith3+                (\x a m -> x .&. m == a .&. m)+                (B.unpack n)+                (B.unpack addr)+                (B.unpack mask)+            )+            then Matched+            else NotMatched+  where+    (addr, mask) = B.splitAt (B.length n) c++doCriticalExtensionSweep :: Certificate -> [FailedReason]+doCriticalExtensionSweep cert = case mexts of+    Nothing -> []+    Just exts ->+        [ UnknownCriticalExtension oid+        | ExtensionRaw oid critical _ <- exts+        , critical+        , oid `notElem` recognizedOIDs+        ]+  where+    Extensions mexts = certExtensions cert
Data/X509/Validation/Fingerprint.hs view
@@ -40,3 +40,7 @@     mkHash HashSHA256 = convert . hashWith SHA256     mkHash HashSHA384 = convert . hashWith SHA384     mkHash HashSHA512 = convert . hashWith SHA512+    mkHash HashSHA3_224 = convert . hashWith SHA3_224+    mkHash HashSHA3_256 = convert . hashWith SHA3_256+    mkHash HashSHA3_384 = convert . hashWith SHA3_384+    mkHash HashSHA3_512 = convert . hashWith SHA3_512
+ Data/X509/Validation/Internal.hs view
@@ -0,0 +1,43 @@+{-# LANGUAGE ScopedTypeVariables #-}++-- |+-- Module      : Data.X509.Validation.Internal+-- License     : BSD-style+-- Stability   : experimental+-- Portability : unknown+--+-- Guards against exceptions thrown from pure code on malformed input.+module Data.X509.Validation.Internal (+    tryPure,+    safeCharacterToString,+) where++import Control.Exception (+    SomeAsyncException,+    SomeException,+    evaluate,+    fromException,+    throwIO,+    try,+ )+import Data.ASN1.Types (ASN1CharacterString, asn1CharacterToString)+import qualified Data.List as L+import System.IO.Unsafe (unsafeDupablePerformIO)++-- | Run a forcing function and turn synchronous exceptions into 'Left'.+tryPure :: (a -> ()) -> a -> Either String a+tryPure force x = unsafeDupablePerformIO $ do+    res <- try $ evaluate $ force x+    case res of+        Right () -> return $ Right x+        Left (e :: SomeException)+            | Just (_ :: SomeAsyncException) <- fromException e -> throwIO e+            | otherwise -> return $ Left (show e)+{-# NOINLINE tryPure #-}++-- | Like 'asn1CharacterToString' but 'Nothing' on invalid encoding.+safeCharacterToString :: ASN1CharacterString -> Maybe String+safeCharacterToString cs =+    asn1CharacterToString cs >>= either (const Nothing) Just . tryPure force+  where+    force = L.foldl' (flip seq) ()
Data/X509/Validation/Signature.hs view
@@ -1,3 +1,5 @@+{-# LANGUAGE RankNTypes #-}+ -- | -- Module      : Data.X509.Validation.Signature -- License     : BSD-style@@ -15,11 +17,15 @@  import Crypto.Error (CryptoFailable (..)) import Crypto.Hash+import Crypto.Number.Basic (numBits) import qualified Crypto.PubKey.DSA as DSA import qualified Crypto.PubKey.ECC.ECDSA as ECDSA import qualified Crypto.PubKey.ECC.Types as ECC import qualified Crypto.PubKey.Ed25519 as Ed25519 import qualified Crypto.PubKey.Ed448 as Ed448+import qualified Crypto.PubKey.MLDSA as MLDSA+import Crypto.PubKey.MaskGenFunction (mgf1)+import qualified Crypto.PubKey.RSA as RSA import qualified Crypto.PubKey.RSA.PKCS15 as RSA import qualified Crypto.PubKey.RSA.PSS as PSS @@ -29,6 +35,7 @@ import Data.ByteString (ByteString) import Data.X509 import Data.X509.EC+import Data.X509.Validation.Internal (tryPure)  -- | A set of possible return from signature verification. --@@ -80,22 +87,47 @@     -> ByteString     -- ^ Signature to verify     -> SignatureVerification-verifySignature (SignatureALG_Unknown _) _ _ _ = SignatureFailed SignatureUnimplemented-verifySignature (SignatureALG hashALG PubKeyALG_RSAPSS) pubkey cdata signature = case verifyF pubkey of-    Nothing -> SignatureFailed SignatureUnimplemented-    Just f ->-        if f cdata signature-            then SignaturePass-            else SignatureFailed SignatureInvalid-  where-    verifyF (PubKeyRSA key)-        | hashALG == HashSHA256 = Just $ PSS.verify (PSS.defaultPSSParams SHA256) key-        | hashALG == HashSHA384 = Just $ PSS.verify (PSS.defaultPSSParams SHA384) key-        | hashALG == HashSHA512 = Just $ PSS.verify (PSS.defaultPSSParams SHA512) key-        | hashALG == HashSHA224 = Just $ PSS.verify (PSS.defaultPSSParams SHA224) key-        | otherwise = Nothing-    verifyF _ = Nothing-verifySignature (SignatureALG hashALG pubkeyALG) pubkey cdata signature+verifySignature alg pubkey cdata signature+    | not (acceptablePubKey pubkey) = SignatureFailed SignatureInvalid+    | weakHash alg = SignatureFailed SignatureUnimplemented+    | otherwise =+        -- degenerate keys or encodings must not throw from pure code+        either (const $ SignatureFailed SignatureInvalid) id $+            tryPure (`seq` ()) (verifySignature' alg pubkey cdata signature)++-- | MD2 and MD5 are broken for signatures.+weakHash :: SignatureALG -> Bool+weakHash (SignatureALG h _) = h `elem` [HashMD2, HashMD5]+weakHash _ = False++-- | Reject key parameters that are invalid or too costly to verify with.+acceptablePubKey :: PubKey -> Bool+acceptablePubKey (PubKeyRSA key) = acceptableRSA key+acceptablePubKey (PubKeyRSAPSS key _) = acceptableRSA key+acceptablePubKey (PubKeyDSA (DSA.PublicKey (DSA.Params p g q) y)) =+    p > 2+        && numBits p <= 8192+        && q > 1+        && q < p+        && numBits q <= 512+        && g > 1+        && g < p+        && y > 1+        && y < p+acceptablePubKey _ = True++acceptableRSA :: RSA.PublicKey -> Bool+acceptableRSA (RSA.PublicKey _ n e) =+    n > 1 && numBits n <= 16384 && e > 1 && numBits e <= 64++verifySignature'+    :: SignatureALG -> PubKey -> ByteString -> ByteString -> SignatureVerification+verifySignature' (SignatureALG_Unknown _) _ _ _ = SignatureFailed SignatureUnimplemented+verifySignature' (SignatureALG hashALG PubKeyALG_RSAPSS) pubkey cdata signature =+    verifyPSS (defaultPSSParams hashALG) pubkey cdata signature+verifySignature' (SignatureALG_RSAPSS params) pubkey cdata signature =+    verifyPSS params pubkey cdata signature+verifySignature' (SignatureALG hashALG pubkeyALG) pubkey cdata signature     | pubkeyToAlg pubkey == pubkeyALG = case verifyF pubkey of         Nothing -> SignatureFailed SignatureUnimplemented         Just f ->@@ -115,33 +147,37 @@      dsaToSignature :: ByteString -> Maybe DSA.Signature     dsaToSignature b =-        case decodeASN1' BER b of-            Left _ -> Nothing-            Right asn1 ->-                case asn1 of-                    Start Sequence : IntVal r : IntVal s : End Sequence : _ ->-                        Just $ DSA.Signature{DSA.sign_r = r, DSA.sign_s = s}-                    _ ->-                        Nothing+        case decodeASN1' DER b of+            Right [Start Sequence, IntVal r, IntVal s, End Sequence] ->+                Just $ DSA.Signature{DSA.sign_r = r, DSA.sign_s = s}+            _ -> Nothing      dsaVerify hsh key b a =         case dsaToSignature a of             Nothing -> False             Just dsaSig -> DSA.verify hsh key dsaSig b -    rsaVerify HashMD2 = RSA.verify (Just MD2)-    rsaVerify HashMD5 = RSA.verify (Just MD5)-    rsaVerify HashSHA1 = RSA.verify (Just SHA1)-    rsaVerify HashSHA224 = RSA.verify (Just SHA224)-    rsaVerify HashSHA256 = RSA.verify (Just SHA256)-    rsaVerify HashSHA384 = RSA.verify (Just SHA384)-    rsaVerify HashSHA512 = RSA.verify (Just SHA512)-verifySignature (SignatureALG_IntrinsicHash pubkeyALG) pubkey cdata signature+    rsaVerify HashMD2 = rsaVerifyWith MD2+    rsaVerify HashMD5 = rsaVerifyWith MD5+    rsaVerify HashSHA1 = rsaVerifyWith SHA1+    rsaVerify HashSHA224 = rsaVerifyWith SHA224+    rsaVerify HashSHA256 = rsaVerifyWith SHA256+    rsaVerify HashSHA384 = rsaVerifyWith SHA384+    rsaVerify HashSHA512 = rsaVerifyWith SHA512+    rsaVerify HashSHA3_224 = rsaVerifyWith SHA3_224+    rsaVerify HashSHA3_256 = rsaVerifyWith SHA3_256+    rsaVerify HashSHA3_384 = rsaVerifyWith SHA3_384+    rsaVerify HashSHA3_512 = rsaVerifyWith SHA3_512+    rsaVerifyWith h key msg = RSA.verifyDigest key (hashWith h msg)+verifySignature' (SignatureALG_IntrinsicHash pubkeyALG) pubkey cdata signature     | pubkeyToAlg pubkey == pubkeyALG = doVerify pubkey     | otherwise = SignatureFailed SignaturePubkeyMismatch   where     doVerify (PubKeyEd25519 key) = eddsa Ed25519.verify Ed25519.signature key     doVerify (PubKeyEd448 key) = eddsa Ed448.verify Ed448.signature key+    doVerify (PubKeyMLDSA44 key) = mldsa key+    doVerify (PubKeyMLDSA65 key) = mldsa key+    doVerify (PubKeyMLDSA87 key) = mldsa key     doVerify _ = SignatureFailed SignatureUnimplemented      eddsa verify toSig key =@@ -151,12 +187,60 @@                 | otherwise -> SignatureFailed SignatureInvalid             CryptoFailed _ -> SignatureFailed SignatureInvalid +    -- RFC 9881 Section 3: the empty context string.+    mldsa :: MLDSA.MLDSA p => MLDSA.VerificationKey p -> SignatureVerification+    mldsa key =+        case MLDSA.signature signature of+            CryptoPassed sig+                | MLDSA.verify key MLDSA.emptyContext cdata sig -> SignaturePass+                | otherwise -> SignatureFailed SignatureInvalid+            CryptoFailed _ -> SignatureFailed SignatureInvalid++verifyPSS+    :: PSSParams -> PubKey -> ByteString -> ByteString -> SignatureVerification+verifyPSS params (PubKeyRSAPSS key mkp) cdata signature+    -- RFC 4055 3.3: the hash and MGF must match and the salt is not shorter+    | Just kp <- mkp+    , pssHash params /= pssHash kp+        || pssMGFHash params /= pssMGFHash kp+        || pssSaltLength params < pssSaltLength kp =+        SignatureFailed SignaturePubkeyMismatch+    | otherwise = verifyPSS params (PubKeyRSA key) cdata signature+verifyPSS params (PubKeyRSA key) cdata signature =+    case withPSSHash (pssHash params) $ \h -> withPSSHash (pssMGFHash params) $ \m ->+        Just (PSS.verify (pssParams h m) key cdata signature) of+        Nothing -> SignatureFailed SignatureUnimplemented+        Just True -> SignaturePass+        Just False -> SignatureFailed SignatureInvalid+  where+    pssParams h m =+        PSS.PSSParams+            { PSS.pssHash = h+            , PSS.pssMaskGenAlg = mgf1 m+            , PSS.pssSaltLength = pssSaltLength params+            , PSS.pssTrailerField = 0xbc+            }+verifyPSS _ _ _ _ = SignatureFailed SignaturePubkeyMismatch++withPSSHash+    :: HashALG -> (forall a. HashAlgorithm a => a -> Maybe r) -> Maybe r+withPSSHash HashSHA1 f = f SHA1+withPSSHash HashSHA224 f = f SHA224+withPSSHash HashSHA256 f = f SHA256+withPSSHash HashSHA384 f = f SHA384+withPSSHash HashSHA512 f = f SHA512+withPSSHash HashSHA3_224 f = f SHA3_224+withPSSHash HashSHA3_256 f = f SHA3_256+withPSSHash HashSHA3_384 f = f SHA3_384+withPSSHash HashSHA3_512 f = f SHA3_512+withPSSHash _ _ = Nothing+ verifyECDSA :: HashALG -> PubKeyEC -> Maybe (ByteString -> ByteString -> Bool) verifyECDSA hashALG key =     ecPubKeyCurveName key >>= verifyCurve (pubkeyEC_pub key)   where     verifyCurve pub curveName = Just $ \msg sigBS ->-        case decodeASN1' BER sigBS of+        case decodeASN1' DER sigBS of             Left _ -> False             Right [Start Sequence, IntVal r, IntVal s, End Sequence] ->                 let curve = ECC.getCurveByName curveName@@ -174,3 +258,7 @@     ecdsaVerify HashSHA256 = ECDSA.verify SHA256     ecdsaVerify HashSHA384 = ECDSA.verify SHA384     ecdsaVerify HashSHA512 = ECDSA.verify SHA512+    ecdsaVerify HashSHA3_224 = ECDSA.verify SHA3_224+    ecdsaVerify HashSHA3_256 = ECDSA.verify SHA3_256+    ecdsaVerify HashSHA3_384 = ECDSA.verify SHA3_384+    ecdsaVerify HashSHA3_512 = ECDSA.verify SHA3_512
Tests/Certificate.hs view
@@ -1,4 +1,5 @@ {-# LANGUAGE GADTs #-}+{-# LANGUAGE TypeOperators #-}  -- | Types and functions used to build test certificates. module Certificate (@@ -10,6 +11,8 @@     hashSHA256,     hashSHA384,     hashSHA512,+    hashSHA3_256,+    hashSHA3_384,      -- * Key and signature utilities     Alg (..),@@ -29,8 +32,7 @@     mkLeaf, ) where -import Control.Applicative-+import Crypto.Hash (hashWith) import Crypto.Hash.Algorithms import Crypto.Number.Serialize @@ -40,6 +42,7 @@ import qualified Crypto.PubKey.ECC.Types as ECC import qualified Crypto.PubKey.Ed25519 as Ed25519 import qualified Crypto.PubKey.Ed448 as Ed448+import qualified Crypto.PubKey.MLDSA as MLDSA import qualified Crypto.PubKey.RSA as RSA import qualified Crypto.PubKey.RSA.PKCS15 as RSA import qualified Crypto.PubKey.RSA.PSS as PSS@@ -51,6 +54,7 @@ import Data.ASN1.Types import Data.ByteArray (convert) import Data.Maybe (catMaybes)+import Data.Proxy (Proxy (..)) import Data.String (fromString) import Data.X509 @@ -78,6 +82,11 @@ hashSHA384 = GHash HashSHA384 SHA384 hashSHA512 = GHash HashSHA512 SHA512 +hashSHA3_256 :: GHash SHA3_256+hashSHA3_384 :: GHash SHA3_384+hashSHA3_256 = GHash HashSHA3_256 SHA3_256+hashSHA3_384 = GHash HashSHA3_384 SHA3_384+ -- | Signature and hash algorithms instantiated with parameters. data Alg pub priv where     AlgRSA@@ -103,6 +112,12 @@         -> Alg ECDSA.PublicKey ECDSA.PrivateKey     AlgEd25519 :: Alg Ed25519.PublicKey Ed25519.SecretKey     AlgEd448 :: Alg Ed448.PublicKey Ed448.SecretKey+    AlgMLDSA44+        :: Alg (MLDSA.VerificationKey MLDSA.MLDSA44) (MLDSA.SigningKey MLDSA.MLDSA44)+    AlgMLDSA65+        :: Alg (MLDSA.VerificationKey MLDSA.MLDSA65) (MLDSA.SigningKey MLDSA.MLDSA65)+    AlgMLDSA87+        :: Alg (MLDSA.VerificationKey MLDSA.MLDSA87) (MLDSA.SigningKey MLDSA.MLDSA87)  -- | Types of public and private keys used by a signature algorithm. type Keys pub priv = (Alg pub priv, pub, priv)@@ -125,7 +140,16 @@ generateKeys alg@AlgEd448 = do     secret <- Ed448.generateSecretKey     return (alg, Ed448.toPublic secret, secret)+generateKeys alg@AlgMLDSA44 =+    withAlg alg <$> MLDSA.generateKeyPair (Proxy :: Proxy MLDSA.MLDSA44)+generateKeys alg@AlgMLDSA65 =+    withAlg alg <$> MLDSA.generateKeyPair (Proxy :: Proxy MLDSA.MLDSA65)+generateKeys alg@AlgMLDSA87 =+    withAlg alg <$> MLDSA.generateKeyPair (Proxy :: Proxy MLDSA.MLDSA87) +withAlg :: Alg pub priv -> (pub, priv) -> Keys pub priv+withAlg alg (pub, priv) = (alg, pub, priv)+ generateRSAKeys     :: Alg RSA.PublicKey RSA.PrivateKey     -> Int@@ -142,13 +166,18 @@ getPubKey (AlgDSA _ _) key = PubKeyDSA key getPubKey (AlgEC name _) key = PubKeyEC (PubKeyEC_Named name pub)   where-    ECC.Point x y = ECDSA.public_q key     pub = SerializedPoint bs-    bs = B.cons 4 (i2ospOf_ bytes x `B.append` i2ospOf_ bytes y)+    -- a generated public key is never the point at infinity+    bs = case ECDSA.public_q key of+        ECC.Point x y -> B.cons 4 (i2ospOf_ bytes x `B.append` i2ospOf_ bytes y)+        ECC.PointO -> B.singleton 0     bits = ECC.curveSizeBits (ECC.getCurveByName name)     bytes = (bits + 7) `div` 8 getPubKey AlgEd25519 key = PubKeyEd25519 key getPubKey AlgEd448 key = PubKeyEd448 key+getPubKey AlgMLDSA44 key = PubKeyMLDSA44 key+getPubKey AlgMLDSA65 key = PubKeyMLDSA65 key+getPubKey AlgMLDSA87 key = PubKeyMLDSA87 key  getSignatureALG :: Alg pub priv -> SignatureALG getSignatureALG (AlgRSA _ hash) = SignatureALG (getHashALG hash) PubKeyALG_RSA@@ -157,10 +186,13 @@ getSignatureALG (AlgEC _ hash) = SignatureALG (getHashALG hash) PubKeyALG_EC getSignatureALG AlgEd25519 = SignatureALG_IntrinsicHash PubKeyALG_Ed25519 getSignatureALG AlgEd448 = SignatureALG_IntrinsicHash PubKeyALG_Ed448+getSignatureALG AlgMLDSA44 = SignatureALG_IntrinsicHash PubKeyALG_MLDSA44+getSignatureALG AlgMLDSA65 = SignatureALG_IntrinsicHash PubKeyALG_MLDSA65+getSignatureALG AlgMLDSA87 = SignatureALG_IntrinsicHash PubKeyALG_MLDSA87  doSign :: Alg pub priv -> priv -> B.ByteString -> IO B.ByteString doSign (AlgRSA _ hash) key msg = do-    result <- RSA.signSafer (Just $ getHashAlgorithm hash) key msg+    result <- RSA.signSaferDigest key (hashWith (getHashAlgorithm hash) msg)     case result of         Left err -> error ("doSign(AlgRSA): " ++ show err)         Right sigBits -> return sigBits@@ -193,6 +225,9 @@     return $ convert $ Ed25519.sign key (Ed25519.toPublic key) msg doSign AlgEd448 key msg =     return $ convert $ Ed448.sign key (Ed448.toPublic key) msg+doSign AlgMLDSA44 key msg = convert <$> MLDSA.sign key MLDSA.emptyContext msg+doSign AlgMLDSA65 key msg = convert <$> MLDSA.sign key MLDSA.emptyContext msg+doSign AlgMLDSA87 key msg = convert <$> MLDSA.sign key MLDSA.emptyContext msg  -- Certificate utilities -- 
Tests/Tests.hs view
@@ -1,17 +1,23 @@ -- | Validation test suite. module Main (main) where -import Control.Applicative import Control.Monad (unless)  import Crypto.Hash.Algorithms  import qualified Crypto.PubKey.DSA as DSA+import qualified Crypto.PubKey.ECC.ECDSA as ECDSA import qualified Crypto.PubKey.ECC.Types as ECC+import Crypto.PubKey.MaskGenFunction (mgf1)+import qualified Crypto.PubKey.RSA as RSA import qualified Crypto.PubKey.RSA.PSS as PSS +import Data.ASN1.BinaryEncoding (DER (..))+import Data.ASN1.BitArray (toBitArray)+import Data.ASN1.Encoding (encodeASN1')+import Data.ASN1.Types+ import Data.Default-import Data.Monoid import Data.String (fromString) import Data.X509 import Data.X509.CertificateStore@@ -20,7 +26,7 @@ import qualified Data.ByteString as BS  import Data.Hourglass-import System.Hourglass+import Time.System  import Test.Tasty import Test.Tasty.HUnit@@ -556,6 +562,37 @@                 , AltNameDNS "dummy2"                 ] +-- | Tests a host name against a certificate with the given CN and,+-- if any, SubjectAltName entries.+testNames+    :: IO (RData pub priv)+    -> TestName+    -> String+    -- ^ Certificate CN+    -> Maybe [AltName]+    -- ^ Certificate SubjectAltName+    -> HostName+    -> [FailedReason]+    -> TestTree+testNames res caseName cn san hostname expected = testWithRes res caseName $ \rd -> do+    pair <-+        mkCertificate+            2+            100+            (mkDn cn)+            (present rd)+            (exts ++ leafStdExts)+            (CA $ intermediate rd)+            (keys1 rd)+    assertValidationResult+        rd+        defaultChecks+        hostname+        [pair, intermediate rd]+        expected+  where+    exts = maybe [] (\ns -> [mkExtension False $ ExtSubjectAltName ns]) san+ -- | Tests 'checkLeafKeyUsage'. testLeafKeyUsage     :: IO (RData pub priv)@@ -621,6 +658,816 @@     caseName = if null hostname then "empty" else hostname     checks = defaultChecks{checkExhaustive = True} +-- | Validates a chain against a store and checks only success or failure.+assertPassOrFail+    :: CertificateStore+    -> ValidationChecks+    -> HostName+    -> [Pair pub priv]+    -> Bool+    -> Assertion+assertPassOrFail store checks hostname ps pass = do+    actual <- validate HashSHA256 defaultHooks checks store def ident chain+    unless (null actual == pass) $+        assertFailure $+            (if pass then "expected success but got: " else "expected failure but got: ")+                ++ show actual+  where+    ident = (hostname, fromString ":443")+    chain = CertificateChain (map pairSignedCert ps)++nameConstraints :: [AltName] -> [AltName] -> ExtensionRaw+nameConstraints p e = mkExtension True $ ExtNameConstraints (map sub p) (map sub e)+  where+    sub a = GeneralSubtree a 0 Nothing++caBC :: ExtensionRaw+caBC = mkExtension True $ ExtBasicConstraints True Nothing++sanExt :: [AltName] -> ExtensionRaw+sanExt = mkExtension False . ExtSubjectAltName++-- | Tests name constraints of an intermediate CA and an optional sub-CA+-- against a leaf certificate.+testNameConstraints+    :: IO (RData pub priv)+    -> TestName+    -> [ExtensionRaw]+    -- ^ Extensions of the CA in addition to basic constraints+    -> Maybe [ExtensionRaw]+    -- ^ Extensions of the sub-CA, if any+    -> DistinguishedName+    -- ^ Leaf subject+    -> [ExtensionRaw]+    -- ^ Leaf extensions+    -> HostName+    -> Bool+    -- ^ Expected success+    -> TestTree+testNameConstraints res caseName caExts msubExts leafDN leafExts hostname pass =+    testWithRes res caseName $ \rd -> do+        ca <-+            mkCertificate+                2+                30+                (mkDn "NC CA")+                (present rd)+                (caBC : caExts)+                (CA $ root rd)+                (keys1 rd)+        (issuer, chain) <- case msubExts of+            Nothing -> return (ca, [ca])+            Just subExts -> do+                sub <-+                    mkCertificate+                        2+                        31+                        (mkDn "NC Sub CA")+                        (present rd)+                        (caBC : subExts)+                        (CA ca)+                        (keys2 rd)+                return (sub, [sub, ca])+        leaf <- mkCertificate 2 100 leafDN (present rd) leafExts (CA issuer) (keys3 rd)+        assertPassOrFail (rootStore rd) defaultChecks hostname (leaf : chain) pass++-- | A leaf whose subject equals the issuer is not exempt from the name+-- constraints of a trust anchor.+testSelfIssuedLeaf :: IO (RData pub priv) -> TestName -> TestTree+testSelfIssuedLeaf res caseName = testWithRes res caseName $ \rd -> do+    let exts = [caBC, nameConstraints [AltNameDNS "example.com"] []]+    anchor <- mkCertificate 2 40 (mkDn "NC Root") (present rd) exts Self (keys1 rd)+    leaf <-+        mkCertificate+            2+            41+            (mkDn "NC Root")+            (present rd)+            [sanExt [AltNameDNS "www.google.com"]]+            (CA anchor)+            (keys2 rd)+    assertPassOrFail (mkStore [anchor]) defaultChecks "www.google.com" [leaf] False++-- | Tests a chain longer than the supported depth.+testLongChain :: IO (RData pub priv) -> TestName -> Int -> Bool -> TestTree+testLongChain res caseName len pass = testWithRes res caseName $ \rd -> do+    let mk issuer i =+            mkCertificate+                2+                (fromIntegral i)+                (mkDn ("CA" ++ show i))+                (present rd)+                [caBC]+                (CA issuer)+                (keys1 rd)+        go issuer i acc+            | i > len = return (issuer, acc)+            | otherwise = mk issuer i >>= \c -> go c (i + 1) (c : acc)+    (lastCA, cas) <- go (root rd) (1 :: Int) []+    leaf <- mkLeaf "long-chain" (present rd) (CA lastCA) (keys2 rd)+    assertPassOrFail (rootStore rd) defaultChecks "long-chain" (leaf : cas) pass++-- | Tests a CA or leaf with an extension that cannot be decoded.+testMalformedExt+    :: IO (RData pub priv)+    -> TestName+    -> Bool+    -> ExtensionRaw+    -> ValidationChecks+    -> [FailedReason]+    -> TestTree+testMalformedExt res caseName onCA ext checks expected = testWithRes res caseName $ \rd -> do+    ca <-+        mkCertificate+            2+            50+            (mkDn "Malformed CA")+            (present rd)+            ([ext | onCA] ++ [caBC | not (isBC ext)])+            (CA $ root rd)+            (keys1 rd)+    leaf <-+        mkCertificate+            2+            100+            (mkDn "malformed")+            (present rd)+            ([ext | not onCA])+            (CA ca)+            (keys2 rd)+    assertValidationResult rd checks "malformed" [leaf, ca] expected+  where+    isBC (ExtensionRaw oid _ _) = oid == [2, 5, 29, 19]++-- | Signature verification with degenerate or oversized keys fails.+testBadKeys :: TestTree+testBadKeys =+    testGroup+        "bad-keys"+        [ testCase "DSA p=0" $+            verifySignature+                (SignatureALG HashSHA256 PubKeyALG_DSA)+                (PubKeyDSA (DSA.PublicKey (DSA.Params 0 2 7) 3))+                (BS.pack [1, 2, 3])+                (encodeASN1' DER [Start Sequence, IntVal 1, IntVal 1, End Sequence])+                @?= SignatureFailed SignatureInvalid+        , testCase "huge RSA modulus" $+            verifySignature+                (SignatureALG HashSHA256 PubKeyALG_RSA)+                (PubKeyRSA (RSA.PublicKey 2049 (2 ^ (16392 :: Int) - 1) 3))+                (BS.pack [1, 2, 3])+                (BS.replicate 2049 1)+                @?= SignatureFailed SignatureInvalid+        , testCase "huge RSA exponent" $+            verifySignature+                (SignatureALG HashSHA256 PubKeyALG_RSA)+                (PubKeyRSA (RSA.PublicKey 256 (2 ^ (2048 :: Int) - 1) (2 ^ (2047 :: Int) + 1)))+                (BS.pack [1, 2, 3])+                (BS.replicate 256 1)+                @?= SignatureFailed SignatureInvalid+        , testCase "tiny RSA-PSS modulus" $+            verifySignature+                (SignatureALG HashSHA256 PubKeyALG_RSAPSS)+                (PubKeyRSA (RSA.PublicKey 1 0x7f 3))+                (BS.pack [1, 2, 3])+                (BS.pack [1])+                @?= SignatureFailed SignatureInvalid+        ]++-- | RSA-PSS signatures are verified with their own parameters.+testPSSParams :: TestTree+testPSSParams = testCase "RSA-PSS parameters" $ do+    (pub, priv) <- RSA.generate 128 3+    let msg = BS.pack [1, 2, 3]+        params :: PSS.PSSParams SHA384 BS.ByteString BS.ByteString+        params =+            PSS.PSSParams+                { PSS.pssHash = SHA384+                , PSS.pssMaskGenAlg = mgf1 SHA256+                , PSS.pssSaltLength = 0+                , PSS.pssTrailerField = 0xbc+                }+        alg =+            rsaPSSSignatureALG $+                (defaultPSSParams HashSHA384){pssMGFHash = HashSHA256, pssSaltLength = 0}+    sig <- either (error . show) id <$> PSS.signSafer params priv msg+    verifySignature alg (PubKeyRSA pub) msg sig @?= SignaturePass+    verifySignature+        (SignatureALG HashSHA384 PubKeyALG_RSAPSS)+        (PubKeyRSA pub)+        msg+        sig+        @?= SignatureFailed SignatureInvalid+    -- RSASSA-PSS keys restrict the parameters (RFC 4055 3.3)+    let restricted p = PubKeyRSAPSS pub (Just p)+        custom = (defaultPSSParams HashSHA384){pssMGFHash = HashSHA256, pssSaltLength = 0}+    verifySignature alg (PubKeyRSAPSS pub Nothing) msg sig @?= SignaturePass+    verifySignature alg (restricted custom) msg sig @?= SignaturePass+    verifySignature alg (restricted (defaultPSSParams HashSHA384)) msg sig+        @?= SignatureFailed SignaturePubkeyMismatch+    verifySignature alg (restricted custom{pssMGFHash = HashSHA384}) msg sig+        @?= SignatureFailed SignaturePubkeyMismatch+    verifySignature (SignatureALG HashSHA384 PubKeyALG_RSA) (PubKeyRSAPSS pub Nothing) msg sig+        @?= SignatureFailed SignaturePubkeyMismatch++-- | Validity period around the current date.+currentValidity :: IO (DateTime, DateTime)+currentValidity = do+    today <- timeGetDate <$> timeCurrent+    let d y = mkDateTime $ today `dateAddPeriod` mempty{periodYears = y}+    return (d (-1), d 1)++-- | Validates a chain against a store for www.example.com.+validateExample :: CertificateStore -> [SignedCertificate] -> IO [FailedReason]+validateExample store chain =+    validate+        HashSHA256+        defaultHooks+        defaultChecks+        store+        def+        ("www.example.com", fromString ":443")+        (CertificateChain chain)++exampleSAN :: ExtensionRaw+exampleSAN = sanExt [AltNameDNS "www.example.com"]++-- | A trust anchor that is not a CA can only validate itself.+testNonCAAnchor :: IO (RData pub priv) -> TestTree+testNonCAAnchor res =+    testGroup+        "non-CA anchor"+        [ testWithRes res "as issuer" $ \rd -> do+            anchor <-+                mkCertificate 2 50 (mkDn "NotCA Root") (present rd) [notCA] Self (keys1 rd)+            leaf <-+                mkCertificate+                    2+                    51+                    (mkDn "leaf")+                    (present rd)+                    [exampleSAN]+                    (CA anchor)+                    (keys2 rd)+            actual <- validateExample (mkStore [anchor]) [pairSignedCert leaf]+            actual @?= [NotAnAuthority]+        , testWithRes res "as itself" $ \rd -> do+            self <-+                mkCertificate+                    2+                    52+                    (mkDn "self")+                    (present rd)+                    [notCA, exampleSAN]+                    Self+                    (keys3 rd)+            actual <- validateExample (mkStore [self]) [pairSignedCert self]+            actual @?= []+        ]+  where+    notCA = mkExtension True $ ExtBasicConstraints False Nothing++-- | The outer signature algorithm must match the one in the TBS.+testSignatureAlgMismatch :: TestTree+testSignatureAlgMismatch = testCase "signature algorithm mismatch" $ do+    validity <- currentValidity+    let alg = AlgEC ECC.SEC_p256r1 hashSHA256+    rootPair <-+        generateKeys alg >>= mkCA 1 "Mismatch Root" validity (Just bc) Nothing Self+    let rootCert = signedObject $ getSigned $ pairSignedCert rootPair+        cert =+            Certificate+                { certVersion = 2+                , certSerial = 2+                , certSignatureAlg = SignatureALG HashSHA384 PubKeyALG_EC+                , certIssuerDN = certSubjectDN rootCert+                , certValidity = validity+                , certSubjectDN = mkDn "leaf"+                , certPubKey = certPubKey rootCert+                , certExtensions = Extensions (Just [exampleSAN])+                }+        sign raw = do+            sig <- ECDSA.sign (pairKey rootPair) SHA256 raw+            let der =+                    encodeASN1'+                        DER+                        [ Start Sequence+                        , IntVal (ECDSA.sign_r sig)+                        , IntVal (ECDSA.sign_s sig)+                        , End Sequence+                        ]+            return (der, SignatureALG HashSHA256 PubKeyALG_EC)+    leaf <- objectToSignedExactF sign cert+    actual <- validateExample (mkStore [rootPair]) [leaf]+    actual @?= [InvalidSignature SignatureInvalid]+  where+    bc = ExtBasicConstraints True Nothing++-- | Certificates signed with MD5 are rejected.+testWeakHash :: TestTree+testWeakHash = testCase "MD5 signature" $ do+    validity <- currentValidity+    keys <- generateKeys (AlgRSA 1024 hashMD5)+    rootPair <- mkCA 1 "MD5 Root" validity (Just bc) Nothing Self keys+    leaf <- mkCertificate 2 2 (mkDn "leaf") validity [exampleSAN] (CA rootPair) keys+    actual <- validateExample (mkStore [rootPair]) [pairSignedCert leaf]+    actual @?= [InvalidSignature SignatureUnimplemented]+  where+    bc = ExtBasicConstraints True Nothing++-- | A root re-keyed under the same name: both are kept in the store.+testSameNameRoots :: IO (RData pub priv) -> TestTree+testSameNameRoots res = testWithRes res "same-name roots" $ \rd -> do+    old <- mkCertificate 2 60 (mkDn "Same Root") (present rd) [caBC] Self (keys1 rd)+    new <- mkCertificate 2 61 (mkDn "Same Root") (present rd) [caBC] Self (keys2 rd)+    leaf <-+        mkCertificate 2 62 (mkDn "leaf") (present rd) [exampleSAN] (CA old) (keys3 rd)+    actual <- validateExample (mkStore [old, new]) [pairSignedCert leaf]+    actual @?= []++-- | The first intermediate with the issuer name is not the issuer.+testBacktracking :: IO (RData pub priv) -> TestTree+testBacktracking res = testWithRes res "backtracking" $ \rd -> do+    other <-+        mkCertificate 2 70 (mkDn "Other Root") (present rd) [caBC] Self (keys1 rd)+    wrong <-+        mkCertificate 2 71 (mkDn "Same CA") (present rd) [caBC] (CA other) (keys2 rd)+    right <-+        mkCertificate+            2+            72+            (mkDn "Same CA")+            (present rd)+            [caBC]+            (CA (root rd))+            (keys3 rd)+    leaf <-+        mkCertificate 2 73 (mkDn "leaf") (present rd) [exampleSAN] (CA right) (keys1 rd)+    actual <-+        validateExample+            (mkStore [root rd, other])+            (map pairSignedCert [leaf, wrong, right])+    actual @?= []++-- | Many certificates with the same names do not make path building+-- exponential.+testPathBudget :: IO (RData pub priv) -> TestTree+testPathBudget res =+    localOption (mkTimeout 10000000) $+        testWithRes res "path budget" $ \rd -> do+            a0 <- mkCertificate 2 80 (mkDn "Loop A") (present rd) [caBC] Self (keys1 rd)+            let mk dn i issuer = mkCertificate 2 i (mkDn dn) (present rd) [caBC] (CA issuer) (keys1 rd)+            bs@(b1 : _) <- mapM (mk "Loop B" 90 . const a0) [1 .. 6 :: Int]+            as@(a1 : _) <- mapM (\i -> mk "Loop A" (100 + i) b1) [1 .. 6]+            leaf <-+                mkCertificate+                    2+                    99+                    (mkDn "leaf")+                    (present rd)+                    [exampleSAN]+                    (CA a1)+                    (keys2 rd)+            -- "Loop A" issued by "Loop B" and vice versa, all with one key+            let chain = leaf : concat (zipWith (\x y -> [x, y]) as bs)+            actual <- validateExample (rootStore rd) (map pairSignedCert chain)+            assertBool "unexpected success" $ not (null actual)++-- | Issuer names are compared in canonical form.+testCanonicalIssuer :: TestTree+testCanonicalIssuer = testCase "canonical issuer name" $ do+    validity <- currentValidity+    let alg = AlgEC ECC.SEC_p256r1 hashSHA256+    rootPair <-+        generateKeys alg+            >>= mkCA+                1+                "Case Root"+                validity+                (Just $ ExtBasicConstraints True Nothing)+                Nothing+                Self+    let rootCert = signedObject $ getSigned $ pairSignedCert rootPair+        sigAlg = SignatureALG HashSHA256 PubKeyALG_EC+        cert =+            Certificate+                { certVersion = 2+                , certSerial = 2+                , certSignatureAlg = sigAlg+                , certIssuerDN =+                    DistinguishedName+                        [(getObjectID DnCommonName, asn1CharacterString Printable "CASE  root")]+                , certValidity = validity+                , certSubjectDN = mkDn "leaf"+                , certPubKey = certPubKey rootCert+                , certExtensions = Extensions (Just [exampleSAN])+                }+        sign raw = do+            sig <- ECDSA.sign (pairKey rootPair) SHA256 raw+            let der =+                    encodeASN1'+                        DER+                        [ Start Sequence+                        , IntVal (ECDSA.sign_r sig)+                        , IntVal (ECDSA.sign_s sig)+                        , End Sequence+                        ]+            return (der, sigAlg)+    leaf <- objectToSignedExactF sign cert+    actual <- validateExample (mkStore [rootPair]) [leaf]+    actual @?= []++-- | SHA-1 signatures are accepted by default and rejected on request.+testRejectSHA1 :: TestTree+testRejectSHA1 = testCase "SHA-1 signature" $ do+    validity <- currentValidity+    keys <- generateKeys (AlgRSA 1024 hashSHA1)+    rootPair <- mkCA 1 "SHA1 Root" validity (Just bc) Nothing Self keys+    leaf <- mkCertificate 2 2 (mkDn "leaf") validity [exampleSAN] (CA rootPair) keys+    let run checks =+            validate+                HashSHA256+                defaultHooks+                checks+                (mkStore [rootPair])+                defaultValidationCache+                ("www.example.com", fromString ":443")+                (CertificateChain [pairSignedCert leaf])+    accepted <- run defaultChecks+    accepted @?= []+    rejected <- run defaultChecks{checkRejectSHA1 = True}+    rejected @?= [InvalidSignature SignatureUnimplemented]+  where+    bc = ExtBasicConstraints True Nothing++-- | A hook can return its own reason.+testOtherReason :: IO (RData pub priv) -> TestTree+testOtherReason res = testWithRes res "other reason" $ \rd -> do+    leaf <-+        mkCertificate+            2+            53+            (mkDn "leaf")+            (present rd)+            [exampleSAN]+            (CA (root rd))+            (keys1 rd)+    let hooks = defaultHooks{hookValidateName = \_ _ -> [OtherReason "revoked"]}+    actual <-+        validate+            HashSHA256+            hooks+            defaultChecks+            (rootStore rd)+            defaultValidationCache+            ("www.example.com", fromString ":443")+            (CertificateChain [pairSignedCert leaf])+    actual @?= [OtherReason "revoked"]++-- | Regression tests that do not depend on the signature algorithm.+treeRegression :: TestTree+treeRegression = withResource (initData AlgEd25519) freeData $ \res ->+    testGroup+        "regression"+        [ testGroup+            "hardening"+            [ testNonCAAnchor res+            , testSignatureAlgMismatch+            , testWeakHash+            , testRejectSHA1+            , testOtherReason res+            ]+        , testGroup+            "path building"+            [ testSameNameRoots res+            , testBacktracking res+            , testPathBudget res+            , testCanonicalIssuer+            ]+        , testGroup+            "name-constraints"+            [ testNameConstraints+                res+                "permitted"+                [ncEx]+                Nothing+                leafDN+                [sanExt [dns "www.example.com"]]+                "www.example.com"+                True+            , testNameConstraints+                res+                "not permitted"+                [ncEx]+                Nothing+                leafDN+                [sanExt [dns "www.google.com"]]+                "www.google.com"+                False+            , testNameConstraints+                res+                "sub-CA with excluded only"+                [ncEx]+                (Just [nameConstraints [] [dns "foo.invalid"]])+                leafDN+                [sanExt [dns "www.google.com"]]+                "www.google.com"+                False+            , testNameConstraints+                res+                "sub-CA without constraints"+                [ncEx]+                (Just [])+                leafDN+                [sanExt [dns "www.example.com"]]+                "www.example.com"+                True+            , testNameConstraints+                res+                "sub-CA without constraints (outside)"+                [ncEx]+                (Just [])+                leafDN+                [sanExt [dns "www.google.com"]]+                "www.google.com"+                False+            , testNameConstraints+                res+                "sub-CA permitted outside"+                [ncEx]+                (Just [nameConstraints [dns "google.com"] []])+                leafDN+                [sanExt [dns "www.google.com"]]+                "www.google.com"+                False+            , testNameConstraints+                res+                "CN fallback"+                [ncEx]+                Nothing+                (mkDn "www.google.com")+                []+                "www.google.com"+                False+            , testNameConstraints+                res+                "CN fallback (permitted)"+                [ncEx]+                Nothing+                (mkDn "www.example.com")+                []+                "www.example.com"+                True+            , testNameConstraints+                res+                "excluded upper case"+                [nameConstraints [] [dns "google.com"]]+                Nothing+                leafDN+                [sanExt [dns "WWW.GOOGLE.COM"]]+                "www.google.com"+                False+            , testNameConstraints+                res+                "excluded otherName"+                [nameConstraints [] [upn "a@example.com"]]+                Nothing+                leafDN+                [sanExt [dns "www.example.com", upn "b@example.com"]]+                "www.example.com"+                False+            , testNameConstraints+                res+                "otherName under DNS constraints"+                [nameConstraints [dns "example.com"] []]+                Nothing+                leafDN+                [sanExt [dns "www.example.com", upn "b@example.com"]]+                "www.example.com"+                True+            , testNameConstraints+                res+                "excluded by wildcard"+                [nameConstraints [] [dns "www.example.com"]]+                Nothing+                leafDN+                [sanExt [dns "*.example.com"]]+                "www.example.com"+                False+            , testNameConstraints+                res+                "permitted upper case"+                [nameConstraints [dns "EXAMPLE.com"] []]+                Nothing+                leafDN+                [sanExt [dns "www.example.COM"]]+                "www.example.com"+                True+            , testNameConstraints+                res+                "leading dot"+                [nameConstraints [dns ".example.com"] []]+                Nothing+                leafDN+                [sanExt [dns "www.example.com"]]+                "www.example.com"+                True+            , testNameConstraints+                res+                "leading dot (apex)"+                [nameConstraints [dns ".example.com"] []]+                Nothing+                leafDN+                [sanExt [dns "example.com"]]+                "example.com"+                False+            , testNameConstraints+                res+                "excluded IP"+                [nameConstraints [] [ip [8, 8, 8, 8, 255, 255, 255, 255]]]+                Nothing+                leafDN+                [sanExt [dns "www.example.com", ip [8, 8, 8, 8]]]+                "www.example.com"+                False+            , testNameConstraints+                res+                "permitted IP"+                [nameConstraints [ip [10, 0, 0, 0, 255, 0, 0, 0]] []]+                Nothing+                leafDN+                [sanExt [dns "x.example", ip [10, 1, 2, 3]]]+                "10.1.2.3"+                True+            , testNameConstraints+                res+                "not permitted IP"+                [nameConstraints [ip [10, 0, 0, 0, 255, 0, 0, 0]] []]+                Nothing+                leafDN+                [sanExt [dns "x.example", ip [11, 1, 2, 3]]]+                "11.1.2.3"+                False+            , testNameConstraints+                res+                "IP not constrained by DNS"+                [ncEx]+                Nothing+                leafDN+                [sanExt [dns "www.example.com", ip [8, 8, 8, 8]]]+                "8.8.8.8"+                True+            , testNameConstraints+                res+                "excluded email"+                [nameConstraints [] [AltNameRFC822 "example.org"]]+                Nothing+                leafDN+                [sanExt [dns "www.example.com", AltNameRFC822 "a@EXAMPLE.org"]]+                "www.example.com"+                False+            , testNameConstraints+                res+                "excluded URI"+                [nameConstraints [] [AltNameURI ".example.org"]]+                Nothing+                leafDN+                [sanExt [dns "www.example.com", AltNameURI "https://www.example.org/"]]+                "www.example.com"+                False+            , testNameConstraints+                res+                "permitted DN"+                [nameConstraints [AltNameDN (mkDn "leaf")] []]+                Nothing+                leafDN+                [sanExt [dns "www.example.com"]]+                "www.example.com"+                True+            , testNameConstraints+                res+                "excluded DN"+                [nameConstraints [] [AltNameDN (mkDn "LEAF")]]+                Nothing+                leafDN+                [sanExt [dns "www.example.com"]]+                "www.example.com"+                False+            , testNameConstraints+                res+                "unparsable"+                [ncRegisteredID]+                Nothing+                leafDN+                [sanExt [dns "www.google.com"]]+                "www.google.com"+                False+            , testSelfIssuedLeaf res "self-issued leaf"+            ]+        , testGroup+            "subject-alt-name"+            [ testNameConstraints+                res+                "unknown names skipped"+                []+                Nothing+                leafDN+                [sanUnknown]+                "www.example.com"+                True+            , testNameConstraints+                res+                "undecodable SAN"+                []+                Nothing+                (mkDn "www.example.com")+                [sanBroken]+                "www.example.com"+                False+            ]+        , testGroup+            "malformed-extensions"+            [ testMalformedExt+                res+                "CA key usage"+                True+                (raw [2, 5, 29, 15] [IntVal 1])+                defaultChecks+                [NotAllowedToSign]+            , testMalformedExt+                res+                "CA basic constraints"+                True+                (raw [2, 5, 29, 19] [IntVal 1])+                defaultChecks+                [NotAnAuthority]+            , testMalformedExt+                res+                "leaf key usage bit 9"+                False+                (raw [2, 5, 29, 15] [BitString (toBitArray (BS.pack [0x80, 0x40]) 6)])+                defaultChecks+                    { checkLeafKeyUsage = [KeyUsage_digitalSignature]+                    , checkFQHN = False+                    }+                []+            , testMalformedExt+                res+                "leaf extended key usage"+                False+                (raw [2, 5, 29, 37] [Start Sequence, IntVal 1, End Sequence])+                defaultChecks+                    { checkLeafKeyPurpose = [KeyUsagePurpose_ServerAuth]+                    , checkFQHN = False+                    }+                [LeafKeyPurposeNotAllowed]+            ]+        , testGroup+            "chain-length"+            [ testLongChain res "short" 5 True+            , testLongChain res "too long" 25 False+            ]+        , testBadKeys+        , testPSSParams+        ]+  where+    dns = AltNameDNS+    ip = AltNameIP . BS.pack+    -- Microsoft UPN otherName+    upn u =+        AltNameOther+            [1, 3, 6, 1, 4, 1, 311, 20, 2, 3]+            (encodeASN1' DER [ASN1String $ asn1CharacterString UTF8 u])+    leafDN = mkDn "leaf"+    ncEx = nameConstraints [dns "example.com"] []+    raw oid asn1 = ExtensionRaw oid True (encodeASN1' DER asn1)+    ncRegisteredID =+        raw+            [2, 5, 29, 30]+            [ Start Sequence+            , Start (Container Context 0)+            , Start Sequence+            , Other Context 2 (fromString "example.com")+            , End Sequence+            , Start Sequence+            , Other Context 8 (BS.pack [0x2a, 0x03])+            , End Sequence+            , End (Container Context 0)+            , End Sequence+            ]+    sanUnknown =+        ExtensionRaw [2, 5, 29, 17] False $+            encodeASN1'+                DER+                [ Start Sequence+                , Other Context 8 (BS.pack [0x2a, 0x03])+                , Other Context 2 (fromString "www.example.com")+                , End Sequence+                ]+    sanBroken =+        ExtensionRaw [2, 5, 29, 17] False $+            encodeASN1' DER [Start Sequence, IntVal 1, End Sequence]+ -- | All validation test cases. treeWithAlg :: TestName -> Alg pub priv -> TestTree treeWithAlg groupName alg = withResource (initData alg) freeData $ \res ->@@ -819,6 +1666,7 @@                     True                     [NameMismatch "example.com"]                 , testSubjectAltName res "*.example.com" "www.example.com" True []+                , testSubjectAltName res "*.com" "example.com" True [NameMismatch "example.com"]                 , testSubjectAltName res "*.example.com" "www.EXAMPLE.com" True []                 , testSubjectAltName res "*.example.com" "www2.example.com" True []                 , testSubjectAltName@@ -863,19 +1711,73 @@                     [NameMismatch "266.0.0.1"] -- 266 read in Word8 is 10                 , testSubjectAltNameIP                     res-                    (BS.pack [0x20, 0x01, 0x0d, 0xb8, 0x85, 0xa3, 0, 0, 0, 0, 0x8a, 0x2e, 0x03, 0x70, 0x73, 0x34])+                    ( BS.pack+                        [ 0x20+                        , 0x01+                        , 0x0d+                        , 0xb8+                        , 0x85+                        , 0xa3+                        , 0+                        , 0+                        , 0+                        , 0+                        , 0x8a+                        , 0x2e+                        , 0x03+                        , 0x70+                        , 0x73+                        , 0x34+                        ]+                    )                     "2001:0db8:85a3:0000:0000:8a2e:0370:7334"                     True                     []                 , testSubjectAltNameIP                     res-                    (BS.pack [0x20, 0x01, 0x0d, 0xb8, 0x85, 0xa3, 0, 0, 0, 0, 0x8a, 0x2e, 0x03, 0x70, 0x73, 0x34])+                    ( BS.pack+                        [ 0x20+                        , 0x01+                        , 0x0d+                        , 0xb8+                        , 0x85+                        , 0xa3+                        , 0+                        , 0+                        , 0+                        , 0+                        , 0x8a+                        , 0x2e+                        , 0x03+                        , 0x70+                        , 0x73+                        , 0x34+                        ]+                    )                     "2001:0db8:85a3::8a2e:0370:7334"                     True                     []                 , testSubjectAltNameIP                     res-                    (BS.pack [0x20, 0x01, 0x0d, 0xb8, 0x85, 0xa3, 0, 0, 0, 0, 0x8a, 0x2e, 0x03, 0x70, 0x73, 0x34])+                    ( BS.pack+                        [ 0x20+                        , 0x01+                        , 0x0d+                        , 0xb8+                        , 0x85+                        , 0xa3+                        , 0+                        , 0+                        , 0+                        , 0+                        , 0x8a+                        , 0x2e+                        , 0x03+                        , 0x70+                        , 0x73+                        , 0x34+                        ]+                    )                     "2001:0db8:85a3:0:0:8a2e:0370:7334"                     True                     []@@ -887,6 +1789,58 @@                     []                 ]             , testGroup+                "IP address and CN"+                [ testNames+                    res+                    "IP SAN mismatch, CN match"+                    "10.0.0.1"+                    (Just [AltNameIP (BS.pack [10, 0, 0, 2])])+                    "10.0.0.1"+                    [NameMismatch "10.0.0.1"]+                , testNames+                    res+                    "IP SAN match, CN mismatch"+                    "other"+                    (Just [AltNameIP (BS.pack [10, 0, 0, 1])])+                    "10.0.0.1"+                    []+                , testNames+                    res+                    "IP SAN only, CN host name"+                    "www.example.com"+                    (Just [AltNameIP (BS.pack [10, 0, 0, 1])])+                    "www.example.com"+                    [NameMismatch "www.example.com"]+                , testNames+                    res+                    "no SAN, CN IP"+                    "10.0.0.1"+                    Nothing+                    "10.0.0.1"+                    [NameMismatch "10.0.0.1"]+                , testNames+                    res+                    "no SAN, CN host name"+                    "www.example.com"+                    Nothing+                    "www.example.com"+                    []+                , testNames+                    res+                    "IP in dNSName"+                    "other"+                    (Just [AltNameDNS "10.0.0.1"])+                    "10.0.0.1"+                    [NameMismatch "10.0.0.1"]+                , testNames+                    res+                    "invalid iPAddress length"+                    "other"+                    (Just [AltNameIP (BS.pack [10, 0, 0, 1, 0]), AltNameDNS "www.example.com"])+                    "www.example.com"+                    [NameMismatch "www.example.com"]+                ]+            , testGroup                 "disabled"                 [ testSubjectAltName res "www.example.com" "www.example.com" False []                 , testSubjectAltName res "www.example.com" "www2.example.com" False []@@ -913,6 +1867,12 @@                 [p1, p3]                 [p2, p3]                 [LeafKeyPurposeNotAllowed]+            , testLeafKeyPurpose+                res+                "anyExtendedKeyUsage"+                [p1, KeyUsagePurpose_Unknown [2, 5, 29, 37, 0]]+                [p2, p3]+                []             ]         , testExhaustive             res@@ -942,8 +1902,15 @@             , treeWithAlg "RSAPSS" (AlgRSAPSS 2048 pssParams hashSHA224)             , treeWithAlg "DSA" (AlgDSA dsaParams hashSHA1)             , treeWithAlg "ECDSA" (AlgEC curveName hashSHA512)+            , treeWithAlg "RSA SHA3" (AlgRSA 2048 hashSHA3_256)+            , treeWithAlg "RSAPSS SHA3" (AlgRSAPSS 2048 (PSS.defaultPSSParams SHA3_256) hashSHA3_256)+            , treeWithAlg "ECDSA SHA3" (AlgEC curveName hashSHA3_384)             , treeWithAlg "Ed25519" AlgEd25519             , treeWithAlg "Ed448" AlgEd448+            , treeWithAlg "ML-DSA-44" AlgMLDSA44+            , treeWithAlg "ML-DSA-65" AlgMLDSA65+            , treeWithAlg "ML-DSA-87" AlgMLDSA87+            , treeRegression             ]   where     pssParams = PSS.defaultPSSParams SHA224
crypton-x509-validation.cabal view
@@ -1,63 +1,69 @@-Name:                crypton-x509-validation-version:             1.6.14-Description:         X.509 Certificate and CRL validation. please see README-License:             BSD3-License-file:        LICENSE-Copyright:           Vincent Hanquez <vincent@snarc.org>-Author:              Vincent Hanquez <vincent@snarc.org>-Maintainer:          Kazu Yamamoto <kazu@iij.ad.jp>-Synopsis:            X.509 Certificate and CRL validation-Build-Type:          Simple-Category:            Data-stability:           experimental-Homepage:            https://github.com/kazu-yamamoto/crypton-certificate-Cabal-Version:       >= 1.10+cabal-version:      >=1.10+name:               crypton-x509-validation+version:            1.11.0+license:            BSD3+license-file:       LICENSE+copyright:          Vincent Hanquez <vincent@snarc.org>+maintainer:         Kazu Yamamoto <kazu@iij.ad.jp>+author:             Vincent Hanquez <vincent@snarc.org>+stability:          experimental+homepage:           https://github.com/kazu-yamamoto/crypton-certificate+synopsis:           X.509 Certificate and CRL validation+description:        X.509 Certificate and CRL validation. please see README+category:           Data+build-type:         Simple+extra-source-files: ChangeLog.md -Library-  Default-Language:  Haskell2010-  Build-Depends:     base >= 3 && < 5-                   , bytestring-                   , memory-                   , mtl-                   , containers-                   , hourglass-                   , data-default-                   , pem >= 0.1-                   , asn1-types >= 0.3 && < 0.4-                   , asn1-encoding >= 0.9 && < 0.10-                   , crypton-x509 >= 1.7.5-                   , crypton-x509-store >= 1.6-                   , crypton >= 0.24-                   , iproute >= 1.2.2-  Exposed-modules:   Data.X509.Validation-  Other-modules:     Data.X509.Validation.Signature-                     Data.X509.Validation.Fingerprint-                     Data.X509.Validation.Cache-                     Data.X509.Validation.Types-  ghc-options:       -Wall+source-repository head+    type:     git+    location: https://github.com/kazu-yamamoto/crypton-certificate+    subdir:   crypton-x509-validation -Test-Suite test-x509-validation-  Default-Language:  Haskell2010-  type:              exitcode-stdio-1.0-  hs-source-dirs:    Tests-  Main-is:           Tests.hs-  Other-modules:     Certificate-  Build-Depends:     base >= 3 && < 5-                   , bytestring-                   , memory-                   , data-default-                   , tasty-                   , tasty-hunit-                   , hourglass-                   , asn1-types-                   , asn1-encoding-                   , crypton-x509 >= 1.7.1-                   , crypton-x509-store-                   , crypton-x509-validation-                   , crypton-  ghc-options:       -Wall+library+    exposed-modules:  Data.X509.Validation+    other-modules:+        Data.X509.Validation.Signature+        Data.X509.Validation.Fingerprint+        Data.X509.Validation.Cache+        Data.X509.Validation.Types+        Data.X509.Validation.Internal -source-repository head-  type:     git-  location: https://github.com/kazu-yamamoto/crypton-certificate-  subdir:   x509-validation+    default-language: Haskell2010+    ghc-options:      -Wall+    build-depends:+        base >=3 && <5,+        bytestring,+        containers,+        crypton >=2.2.0 && <2.4,+        crypton-asn1-types >=0.4.1 && <0.5,+        crypton-asn1-encoding >=0.10.0 && <0.11,+        crypton-pem >=0.2.4 && <0.4,+        crypton-x509 >=1.11 && <1.12,+        crypton-x509-store >=1.10.1 && <1.11,+        data-default,+        iproute >=1.2.2,+        mtl,+        ram,+        time-hourglass++test-suite test-x509-validation+    type:             exitcode-stdio-1.0+    main-is:          Tests.hs+    hs-source-dirs:   Tests+    other-modules:    Certificate+    default-language: Haskell2010+    ghc-options:      -Wall+    build-depends:+        base >=3 && <5,+        bytestring,+        crypton,+        crypton-asn1-encoding,+        crypton-asn1-types,+        crypton-x509,+        crypton-x509-store,+        crypton-x509-validation,+        data-default,+        ram,+        tasty,+        tasty-hunit,+        time-hourglass