{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ViewPatterns #-}

-- |
-- Module      : Data.X509.Validation
-- License     : BSD-style
-- Maintainer  : Vincent Hanquez <vincent@snarc.org>
-- Stability   : experimental
-- Portability : unknown
--
-- X.509 Certificate checks and validations routines
--
-- Follows RFC5280 / RFC6818
module Data.X509.Validation (
    module Data.X509.Validation.Types,
    Fingerprint (..),

    -- * Failed validation types
    FailedReason (..),
    SignatureFailure (..),

    -- * Validation configuration types
    ValidationChecks (..),
    ValidationHooks (..),
    defaultChecks,
    defaultHooks,

    -- * Validation
    validate,
    validatePure,
    validateDefault,
    getFingerprint,

    -- * Cache
    module Data.X509.Validation.Cache,

    -- * Signature verification
    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 (ByteString, unpack)
import qualified Data.ByteString as B
import Data.Char (toLower)
import Data.Default
import Data.Hourglass
import Data.IP (IPv4, IPv6, fromIPv4, fromIPv6b, toIPv4, toIPv6)
import Data.List
import Data.Maybe
import Data.Word (Word8)
import Data.X509
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 Text.Read (readMaybe)
import Time.System

-- | Possible reason of certificate and chain failure.
--
-- The values 'InvalidName' and 'InvalidWildcard' are internal-only and are
-- never returned by the validation functions.  'NameMismatch' is returned
-- instead.
data FailedReason
    = -- | certificate contains an unknown critical extension
      UnknownCriticalExtension OID
    | -- | validity ends before checking time
      Expired
    | -- | validity starts after checking time
      InFuture
    | -- | certificate is self signed
      SelfSigned
    | -- | unknown Certificate Authority (CA)
      UnknownCA
    | -- | certificate is not allowed to sign
      NotAllowedToSign
    | -- | not a CA
      NotAnAuthority
    | -- | Violation of the optional Basic constraint's path length
      AuthorityTooDeep
    | -- | Certificate doesn't have any common name (CN)
      NoCommonName
    | -- | Invalid name in certificate
      InvalidName String
    | -- | connection name and certificate do not match
      NameMismatch String
    | -- | invalid wildcard in certificate
      InvalidWildcard
    | -- | the requested key usage is not compatible with the leaf certificate's key usage
      LeafKeyUsageNotAllowed
    | -- | the requested key purpose is not compatible with the leaf certificate's extended key usage
      LeafKeyPurposeNotAllowed
    | -- | Only authorized an X509.V3 certificate as leaf certificate.
      LeafNotV3
    | -- | empty chain of certificate
      EmptyChain
    | -- | the cache explicitely denied this certificate
      CacheSaysNo String
    | -- | signature failed
      InvalidSignature SignatureFailure
    deriving (Int -> FailedReason -> ShowS
[FailedReason] -> ShowS
FailedReason -> [Char]
(Int -> FailedReason -> ShowS)
-> (FailedReason -> [Char])
-> ([FailedReason] -> ShowS)
-> Show FailedReason
forall a.
(Int -> a -> ShowS) -> (a -> [Char]) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> FailedReason -> ShowS
showsPrec :: Int -> FailedReason -> ShowS
$cshow :: FailedReason -> [Char]
show :: FailedReason -> [Char]
$cshowList :: [FailedReason] -> ShowS
showList :: [FailedReason] -> ShowS
Show, FailedReason -> FailedReason -> Bool
(FailedReason -> FailedReason -> Bool)
-> (FailedReason -> FailedReason -> Bool) -> Eq FailedReason
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: FailedReason -> FailedReason -> Bool
== :: FailedReason -> FailedReason -> Bool
$c/= :: FailedReason -> FailedReason -> Bool
/= :: FailedReason -> FailedReason -> Bool
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.
data ValidationChecks = ValidationChecks
    { ValidationChecks -> Bool
checkTimeValidity :: Bool
    -- ^ check time validity of every certificate in the chain.
    -- the make sure that current time is between each validity bounds
    -- in the certificate
    , ValidationChecks -> Maybe DateTime
checkAtTime :: Maybe DateTime
    -- ^ The time when the validity check happens. When set to Nothing,
    -- the current time will be used
    , ValidationChecks -> Bool
checkStrictOrdering :: Bool
    -- ^ Check that no certificate is included that shouldn't be included.
    -- unfortunately despite the specification violation, a lots of
    -- real world server serves useless and usually old certificates
    -- that are not relevant to the certificate sent, in their chain.
    , ValidationChecks -> Bool
checkCAConstraints :: Bool
    -- ^ Check that signing certificate got the CA basic constraint.
    -- this is absolutely not recommended to turn it off.
    , ValidationChecks -> Bool
checkExhaustive :: Bool
    -- ^ Check the whole certificate chain without stopping at the first failure.
    -- Allow gathering a exhaustive list of failure reasons. if this is
    -- turn off, it's absolutely not safe to ignore a failed reason even it doesn't look serious
    -- (e.g. Expired) as other more serious checks would not have been performed.
    , ValidationChecks -> Bool
checkLeafV3 :: Bool
    -- ^ Check that the leaf certificate is version 3. If disable, version 2 certificate
    -- is authorized in leaf position and key usage cannot be checked.
    , ValidationChecks -> [ExtKeyUsageFlag]
checkLeafKeyUsage :: [ExtKeyUsageFlag]
    -- ^ Check that the leaf certificate is authorized to be used for certain usage.
    -- If set to empty list no check are performed, otherwise all the flags is the list
    -- need to exists in the key usage extension. If the extension is not present,
    -- the check will pass and behave as if the certificate key is not restricted to
    -- any specific usage.
    , ValidationChecks -> [ExtKeyUsagePurpose]
checkLeafKeyPurpose :: [ExtKeyUsagePurpose]
    -- ^ Check that the leaf certificate is authorized to be used for certain purpose.
    -- If set to empty list no check are performed, otherwise all the flags is the list
    -- need to exists in the extended key usage extension if present. If the extension is not
    -- present, then the check will pass and behave as if the certificate is not restricted
    -- to any specific purpose.
    , ValidationChecks -> Bool
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.
    }
    deriving (Int -> ValidationChecks -> ShowS
[ValidationChecks] -> ShowS
ValidationChecks -> [Char]
(Int -> ValidationChecks -> ShowS)
-> (ValidationChecks -> [Char])
-> ([ValidationChecks] -> ShowS)
-> Show ValidationChecks
forall a.
(Int -> a -> ShowS) -> (a -> [Char]) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> ValidationChecks -> ShowS
showsPrec :: Int -> ValidationChecks -> ShowS
$cshow :: ValidationChecks -> [Char]
show :: ValidationChecks -> [Char]
$cshowList :: [ValidationChecks] -> ShowS
showList :: [ValidationChecks] -> ShowS
Show, ValidationChecks -> ValidationChecks -> Bool
(ValidationChecks -> ValidationChecks -> Bool)
-> (ValidationChecks -> ValidationChecks -> Bool)
-> Eq ValidationChecks
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: ValidationChecks -> ValidationChecks -> Bool
== :: ValidationChecks -> ValidationChecks -> Bool
$c/= :: ValidationChecks -> ValidationChecks -> Bool
/= :: ValidationChecks -> ValidationChecks -> Bool
Eq)

-- | A set of hooks to manipulate the way the verification works.
--
-- BEWARE, it's easy to change behavior leading to compromised security.
data ValidationHooks = ValidationHooks
    { ValidationHooks -> DistinguishedName -> Certificate -> Bool
hookMatchSubjectIssuer :: DistinguishedName -> Certificate -> Bool
    -- ^ check whether a given issuer 'DistinguishedName' matches the subject
    -- 'DistinguishedName' of a candidate issuer certificate.
    , ValidationHooks -> DateTime -> Certificate -> [FailedReason]
hookValidateTime :: DateTime -> Certificate -> [FailedReason]
    -- ^ check whether the certificate in the second argument is valid at the
    -- time provided in the first argument.  Return an empty list for success
    -- or else one or more failure reasons.
    , ValidationHooks -> [Char] -> Certificate -> [FailedReason]
hookValidateName :: HostName -> Certificate -> [FailedReason]
    -- ^ validate the certificate leaf name with the DNS named used to connect
    , ValidationHooks -> [FailedReason] -> [FailedReason]
hookFilterReason :: [FailedReason] -> [FailedReason]
    -- ^ user filter to modify the list of failure reasons
    }

-- | Default checks to perform
--
-- The default checks are:
-- * Each certificate time is valid
-- * CA constraints is enforced for signing certificate
-- * Leaf certificate is X.509 v3
-- * Check that the FQHN match
defaultChecks :: ValidationChecks
defaultChecks :: ValidationChecks
defaultChecks =
    ValidationChecks
        { checkTimeValidity :: Bool
checkTimeValidity = Bool
True
        , checkAtTime :: Maybe DateTime
checkAtTime = Maybe DateTime
forall a. Maybe a
Nothing
        , checkStrictOrdering :: Bool
checkStrictOrdering = Bool
False
        , checkCAConstraints :: Bool
checkCAConstraints = Bool
True
        , checkExhaustive :: Bool
checkExhaustive = Bool
False
        , checkLeafV3 :: Bool
checkLeafV3 = Bool
True
        , checkLeafKeyUsage :: [ExtKeyUsageFlag]
checkLeafKeyUsage = []
        , checkLeafKeyPurpose :: [ExtKeyUsagePurpose]
checkLeafKeyPurpose = []
        , checkFQHN :: Bool
checkFQHN = Bool
True
        }

instance Default ValidationChecks where
    def :: ValidationChecks
def = ValidationChecks
defaultChecks

-- | Default hooks in the validation process
defaultHooks :: ValidationHooks
defaultHooks :: ValidationHooks
defaultHooks =
    ValidationHooks
        { hookMatchSubjectIssuer :: DistinguishedName -> Certificate -> Bool
hookMatchSubjectIssuer = DistinguishedName -> Certificate -> Bool
matchSI
        , hookValidateTime :: DateTime -> Certificate -> [FailedReason]
hookValidateTime = DateTime -> Certificate -> [FailedReason]
validateTime
        , hookValidateName :: [Char] -> Certificate -> [FailedReason]
hookValidateName = [Char] -> Certificate -> [FailedReason]
validateCertificateName
        , hookFilterReason :: [FailedReason] -> [FailedReason]
hookFilterReason = [FailedReason] -> [FailedReason]
forall a. a -> a
id
        }

instance Default ValidationHooks where
    def :: ValidationHooks
def = ValidationHooks
defaultHooks

-- | Validate using the default hooks and checks and the SHA256 mechanism as hashing mechanism
validateDefault
    :: CertificateStore
    -- ^ The trusted certificate store for CA
    -> ValidationCache
    -- ^ the validation cache callbacks
    -> ServiceID
    -- ^ identification of the connection
    -> CertificateChain
    -- ^ the certificate chain we want to validate
    -> IO [FailedReason]
    -- ^ the return failed reasons (empty list is no failure)
validateDefault :: CertificateStore
-> ValidationCache
-> ServiceID
-> CertificateChain
-> IO [FailedReason]
validateDefault = HashALG
-> ValidationHooks
-> ValidationChecks
-> CertificateStore
-> ValidationCache
-> ServiceID
-> CertificateChain
-> IO [FailedReason]
validate HashALG
HashSHA256 ValidationHooks
defaultHooks ValidationChecks
defaultChecks

-- | X509 validation
--
-- the function first interrogate the cache and if the validation fail,
-- proper verification is done. If the verification pass, the
-- add to cache callback is called.
validate
    :: HashALG
    -- ^ the hash algorithm we want to use for hashing the leaf certificate
    -> ValidationHooks
    -- ^ Hooks to use
    -> ValidationChecks
    -- ^ Checks to do
    -> CertificateStore
    -- ^ The trusted certificate store for CA
    -> ValidationCache
    -- ^ the validation cache callbacks
    -> ServiceID
    -- ^ identification of the connection
    -> CertificateChain
    -- ^ the certificate chain we want to validate
    -> IO [FailedReason]
    -- ^ the return failed reasons (empty list is no failure)
validate :: HashALG
-> ValidationHooks
-> ValidationChecks
-> CertificateStore
-> ValidationCache
-> ServiceID
-> CertificateChain
-> IO [FailedReason]
validate HashALG
_ ValidationHooks
_ ValidationChecks
_ CertificateStore
_ ValidationCache
_ ServiceID
_ (CertificateChain []) = [FailedReason] -> IO [FailedReason]
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return [FailedReason
EmptyChain]
validate HashALG
hashAlg ValidationHooks
hooks ValidationChecks
checks CertificateStore
store ValidationCache
cache ServiceID
ident cc :: CertificateChain
cc@(CertificateChain (SignedExact Certificate
top : [SignedExact Certificate]
_)) = do
    cacheResult <- (ValidationCache -> ValidationCacheQueryCallback
cacheQuery ValidationCache
cache) ServiceID
ident Fingerprint
fingerPrint (SignedExact Certificate -> Certificate
getCertificate SignedExact Certificate
top)
    case cacheResult of
        ValidationCacheResult
ValidationCachePass -> [FailedReason] -> IO [FailedReason]
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return []
        ValidationCacheDenied [Char]
s -> [FailedReason] -> IO [FailedReason]
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return [[Char] -> FailedReason
CacheSaysNo [Char]
s]
        ValidationCacheResult
ValidationCacheUnknown -> do
            validationTime <-
                IO DateTime
-> (DateTime -> IO DateTime) -> Maybe DateTime -> IO DateTime
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Elapsed -> DateTime
forall t1 t2. (Timeable t1, Time t2) => t1 -> t2
timeConvert (Elapsed -> DateTime) -> IO Elapsed -> IO DateTime
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> IO Elapsed
timeCurrent) DateTime -> IO DateTime
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (Maybe DateTime -> IO DateTime) -> Maybe DateTime -> IO DateTime
forall a b. (a -> b) -> a -> b
$ ValidationChecks -> Maybe DateTime
checkAtTime ValidationChecks
checks
            let failedReasons = DateTime
-> ValidationHooks
-> ValidationChecks
-> CertificateStore
-> ServiceID
-> CertificateChain
-> [FailedReason]
validatePure DateTime
validationTime ValidationHooks
hooks ValidationChecks
checks CertificateStore
store ServiceID
ident CertificateChain
cc
            when (null failedReasons) $
                (cacheAdd cache) ident fingerPrint (getCertificate top)
            return failedReasons
  where
    fingerPrint :: Fingerprint
fingerPrint = SignedExact Certificate -> HashALG -> Fingerprint
forall a.
(Show a, Eq a, ASN1Object a) =>
SignedExact a -> HashALG -> Fingerprint
getFingerprint SignedExact Certificate
top HashALG
hashAlg

-- | Validate a certificate chain with explicit pure parameters
validatePure
    :: DateTime
    -- ^ The time for which to check validity for
    -> ValidationHooks
    -- ^ Hooks to use
    -> ValidationChecks
    -- ^ Checks to do
    -> CertificateStore
    -- ^ The trusted certificate store for CA
    -> ServiceID
    -- ^ Identification of the connection
    -> CertificateChain
    -- ^ The certificate chain we want to validate
    -> [FailedReason]
    -- ^ the return failed reasons (empty list is no failure)
validatePure :: DateTime
-> ValidationHooks
-> ValidationChecks
-> CertificateStore
-> ServiceID
-> CertificateChain
-> [FailedReason]
validatePure DateTime
_ ValidationHooks
_ ValidationChecks
_ CertificateStore
_ ServiceID
_ (CertificateChain []) = [FailedReason
EmptyChain]
validatePure DateTime
validationTime ValidationHooks
hooks ValidationChecks
checks CertificateStore
store ([Char]
fqhn, ByteString
_) (CertificateChain (SignedExact Certificate
top : [SignedExact Certificate]
rchain)) =
    ValidationHooks -> [FailedReason] -> [FailedReason]
hookFilterReason
        ValidationHooks
hooks
        ([FailedReason]
doLeafChecks [FailedReason] -> [FailedReason] -> [FailedReason]
|> [FailedReason]
chainFailures [FailedReason] -> [FailedReason] -> [FailedReason]
|> [FailedReason]
-> ([SignedExact Certificate] -> [FailedReason])
-> Maybe [SignedExact Certificate]
-> [FailedReason]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [] [SignedExact Certificate] -> [FailedReason]
doCheckNameConst Maybe [SignedExact Certificate]
mpath)
  where
    ([FailedReason]
chainFailures, Maybe [SignedExact Certificate]
mpath) = State Int ([FailedReason], Maybe [SignedExact Certificate])
-> Int -> ([FailedReason], Maybe [SignedExact Certificate])
forall s a. State s a -> s -> a
evalState (Int
-> SignedExact Certificate
-> [SignedExact Certificate]
-> State Int ([FailedReason], Maybe [SignedExact Certificate])
doCheckChain Int
0 SignedExact Certificate
top [SignedExact Certificate]
rchain) Int
maxSignatureChecks

    isExhaustive :: Bool
    isExhaustive :: Bool
isExhaustive = ValidationChecks -> Bool
checkExhaustive ValidationChecks
checks

    (|>) :: [FailedReason] -> [FailedReason] -> [FailedReason]
    [FailedReason]
a |> :: [FailedReason] -> [FailedReason] -> [FailedReason]
|> [FailedReason]
b = Bool -> [FailedReason] -> [FailedReason] -> [FailedReason]
exhaustive Bool
isExhaustive [FailedReason]
a [FailedReason]
b

    doLeafChecks :: [FailedReason]
    doLeafChecks :: [FailedReason]
doLeafChecks =
        SignedExact Certificate -> [FailedReason]
doNameCheck SignedExact Certificate
top
            [FailedReason] -> [FailedReason] -> [FailedReason]
forall a. [a] -> [a] -> [a]
++ Certificate -> [FailedReason]
doV3Check Certificate
topCert
            [FailedReason] -> [FailedReason] -> [FailedReason]
forall a. [a] -> [a] -> [a]
++ Certificate -> [FailedReason]
doKeyUsageCheck Certificate
topCert
      where
        topCert :: Certificate
topCert = SignedExact Certificate -> Certificate
getCertificate SignedExact Certificate
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]
        -> State Int ([FailedReason], Maybe [SignedCertificate])
    doCheckChain :: Int
-> SignedExact Certificate
-> [SignedExact Certificate]
-> State Int ([FailedReason], Maybe [SignedExact Certificate])
doCheckChain Int
level SignedExact Certificate
current [SignedExact Certificate]
chain
        | Int
level Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
maxChainDepth = ([FailedReason], Maybe [SignedExact Certificate])
-> State Int ([FailedReason], Maybe [SignedExact Certificate])
forall a. a -> StateT Int Identity a
forall (m :: * -> *) a. Monad m => a -> m a
return ([FailedReason
AuthorityTooDeep], Maybe [SignedExact Certificate]
forall a. Maybe a
Nothing)
        | Bool
otherwise =
            (Maybe [SignedExact Certificate]
 -> Maybe [SignedExact Certificate])
-> ([FailedReason], Maybe [SignedExact Certificate])
-> ([FailedReason], Maybe [SignedExact Certificate])
forall a b. (a -> b) -> ([FailedReason], a) -> ([FailedReason], b)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (([SignedExact Certificate] -> [SignedExact Certificate])
-> Maybe [SignedExact Certificate]
-> Maybe [SignedExact Certificate]
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap (SignedExact Certificate
current SignedExact Certificate
-> [SignedExact Certificate] -> [SignedExact Certificate]
forall a. a -> [a] -> [a]
:))
                (([FailedReason], Maybe [SignedExact Certificate])
 -> ([FailedReason], Maybe [SignedExact Certificate]))
-> State Int ([FailedReason], Maybe [SignedExact Certificate])
-> State Int ([FailedReason], Maybe [SignedExact Certificate])
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (Certificate -> [FailedReason]
doCheckCertificate Certificate
cert [FailedReason]
-> State Int ([FailedReason], Maybe [SignedExact Certificate])
-> State Int ([FailedReason], Maybe [SignedExact Certificate])
forall p.
[FailedReason]
-> State Int ([FailedReason], Maybe p)
-> State Int ([FailedReason], Maybe p)
`andThen` State Int ([FailedReason], Maybe [SignedExact Certificate])
issuerChecks)
      where
        cert :: Certificate
cert = SignedExact Certificate -> Certificate
getCertificate SignedExact Certificate
current
        issuerDN :: DistinguishedName
issuerDN = Certificate -> DistinguishedName
certIssuerDN Certificate
cert
        anchors :: [SignedExact Certificate]
anchors = DistinguishedName -> CertificateStore -> [SignedExact Certificate]
findCertificates DistinguishedName
issuerDN CertificateStore
store
        issuerChecks :: State Int ([FailedReason], Maybe [SignedExact Certificate])
issuerChecks
            | [SignedExact Certificate] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [SignedExact Certificate]
anchors Bool -> Bool -> Bool
&& Certificate -> Bool
isSelfSigned Certificate
cert = do
                r <- SignedExact Certificate
-> SignedExact Certificate -> State Int [FailedReason]
checkSignatureM SignedExact Certificate
current SignedExact Certificate
current
                return ([SelfSigned] |> r, Nothing)
            | Bool
otherwise =
                [State Int ([FailedReason], Maybe [SignedExact Certificate])]
-> State Int ([FailedReason], Maybe [SignedExact Certificate])
forall p.
[State Int ([FailedReason], Maybe p)]
-> State Int ([FailedReason], Maybe p)
firstSuccess ([State Int ([FailedReason], Maybe [SignedExact Certificate])]
 -> State Int ([FailedReason], Maybe [SignedExact Certificate]))
-> [State Int ([FailedReason], Maybe [SignedExact Certificate])]
-> State Int ([FailedReason], Maybe [SignedExact Certificate])
forall a b. (a -> b) -> a -> b
$
                    (SignedExact Certificate
 -> State Int ([FailedReason], Maybe [SignedExact Certificate]))
-> [SignedExact Certificate]
-> [State Int ([FailedReason], Maybe [SignedExact Certificate])]
forall a b. (a -> b) -> [a] -> [b]
map SignedExact Certificate
-> State Int ([FailedReason], Maybe [SignedExact Certificate])
anchorCheck [SignedExact Certificate]
anchors
                        [State Int ([FailedReason], Maybe [SignedExact Certificate])]
-> [State Int ([FailedReason], Maybe [SignedExact Certificate])]
-> [State Int ([FailedReason], Maybe [SignedExact Certificate])]
forall a. [a] -> [a] -> [a]
++ [SignedExact Certificate
-> [SignedExact Certificate]
-> State Int ([FailedReason], Maybe [SignedExact Certificate])
chainCheck SignedExact Certificate
i [SignedExact Certificate]
r | (SignedExact Certificate
i, [SignedExact Certificate]
r) <- DistinguishedName
-> [SignedExact Certificate]
-> [(SignedExact Certificate, [SignedExact Certificate])]
findIssuers DistinguishedName
issuerDN [SignedExact Certificate]
chain]
        anchorCheck :: SignedExact Certificate
-> State Int ([FailedReason], Maybe [SignedExact Certificate])
anchorCheck SignedExact Certificate
anchor
            -- an anchor that is not a CA may only be the certificate itself
            | ValidationChecks -> Bool
checkCAConstraints ValidationChecks
checks
                Bool -> Bool -> Bool
&& SignedExact Certificate
anchor SignedExact Certificate -> SignedExact Certificate -> Bool
forall a. Eq a => a -> a -> Bool
/= SignedExact Certificate
current
                Bool -> Bool -> Bool
&& Certificate -> Bool
notCA (SignedExact Certificate -> Certificate
getCertificate SignedExact Certificate
anchor) =
                ([FailedReason], Maybe [SignedExact Certificate])
-> State Int ([FailedReason], Maybe [SignedExact Certificate])
forall a. a -> StateT Int Identity a
forall (m :: * -> *) a. Monad m => a -> m a
return ([FailedReason
NotAnAuthority], Maybe [SignedExact Certificate]
forall a. Maybe a
Nothing)
            | Bool
otherwise = do
                r <- SignedExact Certificate
-> SignedExact Certificate -> State Int [FailedReason]
checkSignatureM SignedExact Certificate
current SignedExact Certificate
anchor
                return (r, Just [anchor])
        chainCheck :: SignedExact Certificate
-> [SignedExact Certificate]
-> State Int ([FailedReason], Maybe [SignedExact Certificate])
chainCheck SignedExact Certificate
issuer [SignedExact Certificate]
remaining = do
            r <- SignedExact Certificate
-> SignedExact Certificate -> State Int [FailedReason]
checkSignatureM SignedExact Certificate
current SignedExact Certificate
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 :: forall p.
[FailedReason]
-> State Int ([FailedReason], Maybe p)
-> State Int ([FailedReason], Maybe p)
andThen [FailedReason]
fs State Int ([FailedReason], Maybe p)
next
        | [FailedReason] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [FailedReason]
fs Bool -> Bool -> Bool
|| Bool
isExhaustive = (\([FailedReason]
fs', Maybe p
p) -> ([FailedReason]
fs [FailedReason] -> [FailedReason] -> [FailedReason]
forall a. [a] -> [a] -> [a]
++ [FailedReason]
fs', Maybe p
p)) (([FailedReason], Maybe p) -> ([FailedReason], Maybe p))
-> State Int ([FailedReason], Maybe p)
-> State Int ([FailedReason], Maybe p)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> State Int ([FailedReason], Maybe p)
next
        | Bool
otherwise = ([FailedReason], Maybe p) -> State Int ([FailedReason], Maybe p)
forall a. a -> StateT Int Identity a
forall (m :: * -> *) a. Monad m => a -> m a
return ([FailedReason]
fs, Maybe p
forall a. Maybe a
Nothing)

    firstSuccess
        :: [State Int ([FailedReason], Maybe p)]
        -> State Int ([FailedReason], Maybe p)
    firstSuccess :: forall p.
[State Int ([FailedReason], Maybe p)]
-> State Int ([FailedReason], Maybe p)
firstSuccess = Maybe ([FailedReason], Maybe p)
-> [StateT Int Identity ([FailedReason], Maybe p)]
-> StateT Int Identity ([FailedReason], Maybe p)
forall {m :: * -> *} {a}.
Monad m =>
Maybe ([FailedReason], Maybe a)
-> [m ([FailedReason], Maybe a)] -> m ([FailedReason], Maybe a)
go Maybe ([FailedReason], Maybe p)
forall a. Maybe a
Nothing
      where
        go :: Maybe ([FailedReason], Maybe a)
-> [m ([FailedReason], Maybe a)] -> m ([FailedReason], Maybe a)
go Maybe ([FailedReason], Maybe a)
failed [] = ([FailedReason], Maybe a) -> m ([FailedReason], Maybe a)
forall a. a -> m a
forall (m :: * -> *) a. Monad m => a -> m a
return (([FailedReason], Maybe a) -> m ([FailedReason], Maybe a))
-> ([FailedReason], Maybe a) -> m ([FailedReason], Maybe a)
forall a b. (a -> b) -> a -> b
$ ([FailedReason], Maybe a)
-> Maybe ([FailedReason], Maybe a) -> ([FailedReason], Maybe a)
forall a. a -> Maybe a -> a
fromMaybe ([FailedReason
UnknownCA], Maybe a
forall a. Maybe a
Nothing) Maybe ([FailedReason], Maybe a)
failed
        go Maybe ([FailedReason], Maybe a)
failed (m ([FailedReason], Maybe a)
m : [m ([FailedReason], Maybe a)]
ms) = do
            r@(fs, _) <- m ([FailedReason], Maybe a)
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 :: SignedExact Certificate
-> SignedExact Certificate -> State Int [FailedReason]
checkSignatureM SignedExact Certificate
signedCert SignedExact Certificate
signingCert = do
        budget <- StateT Int Identity Int
forall s (m :: * -> *). MonadState s m => m s
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 :: DistinguishedName
-> [SignedExact Certificate]
-> [(SignedExact Certificate, [SignedExact Certificate])]
findIssuers DistinguishedName
issuerDN [SignedExact Certificate]
chain
        | ValidationChecks -> Bool
checkStrictOrdering ValidationChecks
checks = case [SignedExact Certificate]
chain of
            SignedExact Certificate
c : [SignedExact Certificate]
cs | SignedExact Certificate -> Bool
matches SignedExact Certificate
c -> [(SignedExact Certificate
c, [SignedExact Certificate]
cs)]
            [SignedExact Certificate]
_ -> []
        | Bool
otherwise =
            [ (SignedExact Certificate
c, [SignedExact Certificate]
before [SignedExact Certificate]
-> [SignedExact Certificate] -> [SignedExact Certificate]
forall a. [a] -> [a] -> [a]
++ [SignedExact Certificate]
after)
            | ([SignedExact Certificate]
before, SignedExact Certificate
c : [SignedExact Certificate]
after) <- [[SignedExact Certificate]]
-> [[SignedExact Certificate]]
-> [([SignedExact Certificate], [SignedExact Certificate])]
forall a b. [a] -> [b] -> [(a, b)]
zip ([SignedExact Certificate] -> [[SignedExact Certificate]]
forall a. [a] -> [[a]]
inits [SignedExact Certificate]
chain) ([SignedExact Certificate] -> [[SignedExact Certificate]]
forall a. [a] -> [[a]]
tails [SignedExact Certificate]
chain)
            , SignedExact Certificate -> Bool
matches SignedExact Certificate
c
            ]
      where
        matches :: SignedExact Certificate -> Bool
matches = DistinguishedName -> Certificate -> Bool
matchSubjectIdentifier DistinguishedName
issuerDN (Certificate -> Bool)
-> (SignedExact Certificate -> Certificate)
-> SignedExact Certificate
-> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SignedExact Certificate -> Certificate
getCertificate

    matchSubjectIdentifier :: DistinguishedName -> Certificate -> Bool
    matchSubjectIdentifier :: DistinguishedName -> Certificate -> Bool
matchSubjectIdentifier = ValidationHooks -> DistinguishedName -> Certificate -> Bool
hookMatchSubjectIssuer ValidationHooks
hooks

    -- we check here that the certificate is allowed to be a certificate
    -- authority, by checking the BasicConstraint extension. We also check,
    -- if present the key usage extension for ability to cert sign. If this
    -- extension is not present, then according to RFC 5280, it's safe to
    -- assume that only cert sign (and crl sign) are allowed by this certificate.
    checkCA :: Int -> Certificate -> [FailedReason]
    checkCA :: Int -> Certificate -> [FailedReason]
checkCA Int
level Certificate
cert
        | Bool -> Bool
not (ValidationChecks -> Bool
checkCAConstraints ValidationChecks
checks) = []
        | [Bool] -> Bool
forall (t :: * -> *). Foldable t => t Bool -> Bool
and [Bool
allowedSign, Bool
allowedCA, Bool
allowedDepth] = []
        | Bool
otherwise =
            (if Bool
allowedSign then [] else [FailedReason
NotAllowedToSign])
                [FailedReason] -> [FailedReason] -> [FailedReason]
forall a. [a] -> [a] -> [a]
++ (if Bool
allowedCA then [] else [FailedReason
NotAnAuthority])
                [FailedReason] -> [FailedReason] -> [FailedReason]
forall a. [a] -> [a] -> [a]
++ (if Bool
allowedDepth then [] else [FailedReason
AuthorityTooDeep])
      where
        extensions :: Extensions
extensions = Certificate -> Extensions
certExtensions Certificate
cert
        -- an extension that cannot be decoded is not treated as absent
        allowedSign :: Bool
allowedSign = case Extensions -> Maybe (Either [Char] ExtKeyUsage)
forall a. Extension a => Extensions -> Maybe (Either [Char] a)
extensionGetE Extensions
extensions of
            Just (Right (ExtKeyUsage [ExtKeyUsageFlag]
flags)) -> ExtKeyUsageFlag
KeyUsage_keyCertSign ExtKeyUsageFlag -> [ExtKeyUsageFlag] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [ExtKeyUsageFlag]
flags
            Just (Left [Char]
_) -> Bool
False
            Maybe (Either [Char] ExtKeyUsage)
Nothing -> Bool
True
        (Bool
allowedCA, Maybe Integer
pathLen) = case Extensions -> Maybe (Either [Char] ExtBasicConstraints)
forall a. Extension a => Extensions -> Maybe (Either [Char] a)
extensionGetE Extensions
extensions of
            Just (Right (ExtBasicConstraints Bool
True Maybe Integer
pl)) -> (Bool
True, Maybe Integer
pl)
            Maybe (Either [Char] ExtBasicConstraints)
_ -> (Bool
False, Maybe Integer
forall a. Maybe a
Nothing)
        allowedDepth :: Bool
allowedDepth = case Maybe Integer
pathLen of
            Maybe Integer
Nothing -> Bool
True
            Just Integer
pl
                | Integer -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Integer
pl Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
>= Int
level -> Bool
True
                | Bool
otherwise -> Bool
False

    doNameCheck :: SignedCertificate -> [FailedReason]
    doNameCheck :: SignedExact Certificate -> [FailedReason]
doNameCheck SignedExact Certificate
cert
        | Bool -> Bool
not (ValidationChecks -> Bool
checkFQHN ValidationChecks
checks) = []
        | Bool
otherwise = (ValidationHooks -> [Char] -> Certificate -> [FailedReason]
hookValidateName ValidationHooks
hooks) [Char]
fqhn (SignedExact Certificate -> Certificate
getCertificate SignedExact Certificate
cert)

    doV3Check :: Certificate -> [FailedReason]
    doV3Check :: Certificate -> [FailedReason]
doV3Check Certificate
cert
        | ValidationChecks -> Bool
checkLeafV3 ValidationChecks
checks = case Certificate -> Int
certVersion Certificate
cert of
            Int
2 {- confusingly it means X509.V3 -} -> []
            Int
_ -> [FailedReason
LeafNotV3]
        | Bool
otherwise = []

    doKeyUsageCheck :: Certificate -> [FailedReason]
    doKeyUsageCheck :: Certificate -> [FailedReason]
doKeyUsageCheck Certificate
cert =
        Maybe (Either [Char] [ExtKeyUsageFlag])
-> [ExtKeyUsageFlag] -> FailedReason -> [FailedReason]
forall {a} {a} {a}. Eq a => Maybe (Either a [a]) -> [a] -> a -> [a]
compareListIfExistAndNotNull
            Maybe (Either [Char] [ExtKeyUsageFlag])
mflags
            (ValidationChecks -> [ExtKeyUsageFlag]
checkLeafKeyUsage ValidationChecks
checks)
            FailedReason
LeafKeyUsageNotAllowed
            [FailedReason] -> [FailedReason] -> [FailedReason]
forall a. [a] -> [a] -> [a]
++ Maybe (Either [Char] [ExtKeyUsagePurpose])
-> [ExtKeyUsagePurpose] -> FailedReason -> [FailedReason]
forall {a} {a} {a}. Eq a => Maybe (Either a [a]) -> [a] -> a -> [a]
compareListIfExistAndNotNull
                Maybe (Either [Char] [ExtKeyUsagePurpose])
mpurposes
                (ValidationChecks -> [ExtKeyUsagePurpose]
checkLeafKeyPurpose ValidationChecks
checks)
                FailedReason
LeafKeyPurposeNotAllowed
      where
        mflags :: Maybe (Either [Char] [ExtKeyUsageFlag])
mflags = case Extensions -> Maybe (Either [Char] ExtKeyUsage)
forall a. Extension a => Extensions -> Maybe (Either [Char] a)
extensionGetE (Extensions -> Maybe (Either [Char] ExtKeyUsage))
-> Extensions -> Maybe (Either [Char] ExtKeyUsage)
forall a b. (a -> b) -> a -> b
$ Certificate -> Extensions
certExtensions Certificate
cert of
            Just (Right (ExtKeyUsage [ExtKeyUsageFlag]
keyflags)) -> Either [Char] [ExtKeyUsageFlag]
-> Maybe (Either [Char] [ExtKeyUsageFlag])
forall a. a -> Maybe a
Just ([ExtKeyUsageFlag] -> Either [Char] [ExtKeyUsageFlag]
forall a b. b -> Either a b
Right [ExtKeyUsageFlag]
keyflags)
            Just (Left [Char]
e) -> Either [Char] [ExtKeyUsageFlag]
-> Maybe (Either [Char] [ExtKeyUsageFlag])
forall a. a -> Maybe a
Just ([Char] -> Either [Char] [ExtKeyUsageFlag]
forall a b. a -> Either a b
Left [Char]
e)
            Maybe (Either [Char] ExtKeyUsage)
Nothing -> Maybe (Either [Char] [ExtKeyUsageFlag])
forall a. Maybe a
Nothing
        mpurposes :: Maybe (Either [Char] [ExtKeyUsagePurpose])
mpurposes = case Extensions -> Maybe (Either [Char] ExtExtendedKeyUsage)
forall a. Extension a => Extensions -> Maybe (Either [Char] a)
extensionGetE (Extensions -> Maybe (Either [Char] ExtExtendedKeyUsage))
-> Extensions -> Maybe (Either [Char] ExtExtendedKeyUsage)
forall a b. (a -> b) -> a -> b
$ Certificate -> Extensions
certExtensions Certificate
cert of
            -- anyExtendedKeyUsage does not restrict the purposes
            Just (Right (ExtExtendedKeyUsage [ExtKeyUsagePurpose]
keyPurposes))
                | [Integer] -> ExtKeyUsagePurpose
KeyUsagePurpose_Unknown [Integer
2, Integer
5, Integer
29, Integer
37, Integer
0] ExtKeyUsagePurpose -> [ExtKeyUsagePurpose] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [ExtKeyUsagePurpose]
keyPurposes -> Maybe (Either [Char] [ExtKeyUsagePurpose])
forall a. Maybe a
Nothing
                | Bool
otherwise -> Either [Char] [ExtKeyUsagePurpose]
-> Maybe (Either [Char] [ExtKeyUsagePurpose])
forall a. a -> Maybe a
Just ([ExtKeyUsagePurpose] -> Either [Char] [ExtKeyUsagePurpose]
forall a b. b -> Either a b
Right [ExtKeyUsagePurpose]
keyPurposes)
            Just (Left [Char]
e) -> Either [Char] [ExtKeyUsagePurpose]
-> Maybe (Either [Char] [ExtKeyUsagePurpose])
forall a. a -> Maybe a
Just ([Char] -> Either [Char] [ExtKeyUsagePurpose]
forall a b. a -> Either a b
Left [Char]
e)
            Maybe (Either [Char] ExtExtendedKeyUsage)
Nothing -> Maybe (Either [Char] [ExtKeyUsagePurpose])
forall a. Maybe a
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]. An undecodable extension always fails.
        compareListIfExistAndNotNull :: Maybe (Either a [a]) -> [a] -> a -> [a]
compareListIfExistAndNotNull Maybe (Either a [a])
Nothing [a]
_ a
_ = []
        compareListIfExistAndNotNull (Just (Left a
_)) [a]
_ a
err = [a
err]
        compareListIfExistAndNotNull (Just (Right [a]
list)) [a]
expected a
err
            | [a] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [a]
expected = []
            | [a] -> [a] -> [a]
forall a. Eq a => [a] -> [a] -> [a]
intersect [a]
expected [a]
list [a] -> [a] -> Bool
forall a. Eq a => a -> a -> Bool
== [a]
expected = []
            | Bool
otherwise = [a
err]

    doCheckCertificate :: Certificate -> [FailedReason]
    doCheckCertificate :: Certificate -> [FailedReason]
doCheckCertificate Certificate
cert =
        Bool -> [(Bool, [FailedReason])] -> [FailedReason]
exhaustiveList
            (ValidationChecks -> Bool
checkExhaustive ValidationChecks
checks)
            [ (ValidationChecks -> Bool
checkTimeValidity ValidationChecks
checks, ValidationHooks -> DateTime -> Certificate -> [FailedReason]
hookValidateTime ValidationHooks
hooks DateTime
validationTime Certificate
cert)
            , (Bool
True, Certificate -> [FailedReason]
doCriticalExtensionSweep Certificate
cert)
            ]
    -- check signature of 'signedCert' against the 'signingCert'
    -- The signature algorithm must also match the signed one in the TBS.
    checkSignature
        :: SignedCertificate -> SignedCertificate -> [FailedReason]
    checkSignature :: SignedExact Certificate
-> SignedExact Certificate -> [FailedReason]
checkSignature SignedExact Certificate
signedCert SignedExact Certificate
signingCert
        | Signed Certificate -> SignatureALG
forall a. (Show a, Eq a, ASN1Object a) => Signed a -> SignatureALG
signedAlg (SignedExact Certificate -> Signed Certificate
forall a. (Show a, Eq a, ASN1Object a) => SignedExact a -> Signed a
getSigned SignedExact Certificate
signedCert) SignatureALG -> SignatureALG -> Bool
forall a. Eq a => a -> a -> Bool
/= Certificate -> SignatureALG
certSignatureAlg (SignedExact Certificate -> Certificate
getCertificate SignedExact Certificate
signedCert) =
            [SignatureFailure -> FailedReason
InvalidSignature SignatureFailure
SignatureInvalid]
        | Bool
otherwise =
            case SignedExact Certificate -> PubKey -> SignatureVerification
forall a.
(Show a, Eq a, ASN1Object a) =>
SignedExact a -> PubKey -> SignatureVerification
verifySignedSignature SignedExact Certificate
signedCert (Certificate -> PubKey
certPubKey (Certificate -> PubKey) -> Certificate -> PubKey
forall a b. (a -> b) -> a -> b
$ SignedExact Certificate -> Certificate
getCertificate SignedExact Certificate
signingCert) of
                SignatureVerification
SignaturePass -> []
                SignatureFailed SignatureFailure
r -> [SignatureFailure -> FailedReason
InvalidSignature SignatureFailure
r]

    -- The path runs from the leaf to the trust anchor.
    doCheckNameConst :: [SignedCertificate] -> [FailedReason]
    doCheckNameConst :: [SignedExact Certificate] -> [FailedReason]
doCheckNameConst [SignedExact Certificate]
path = case [SignedExact Certificate] -> [SignedExact Certificate]
forall a. [a] -> [a]
reverse [SignedExact Certificate]
path of
        SignedExact Certificate
anchor : [SignedExact Certificate]
rest ->
            [NameConstSpec] -> [FailedReason]
checkNameConstraints ([NameConstSpec] -> [FailedReason])
-> [NameConstSpec] -> [FailedReason]
forall a b. (a -> b) -> a -> b
$
                Certificate -> Bool -> NameConstSpec
getNameConstSpec (SignedExact Certificate -> Certificate
getCertificate SignedExact Certificate
anchor) Bool
False
                    NameConstSpec -> [NameConstSpec] -> [NameConstSpec]
forall a. a -> [a] -> [a]
: (Int -> SignedExact Certificate -> NameConstSpec)
-> [Int] -> [SignedExact Certificate] -> [NameConstSpec]
forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith Int -> SignedExact Certificate -> NameConstSpec
forall {a}.
(Eq a, Num a) =>
a -> SignedExact Certificate -> NameConstSpec
spec [[SignedExact Certificate] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [SignedExact Certificate]
rest Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1, [SignedExact Certificate] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [SignedExact Certificate]
rest Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
2 ..] [SignedExact Certificate]
rest
        [] -> []
      where
        -- the level counts from the leaf
        spec :: a -> SignedExact Certificate -> NameConstSpec
spec a
level SignedExact Certificate
c = Certificate -> Bool -> NameConstSpec
getNameConstSpec (SignedExact Certificate -> Certificate
getCertificate SignedExact Certificate
c) (a
level a -> a -> Bool
forall a. Eq a => a -> a -> Bool
== a
0 Bool -> Bool -> Bool
&& ValidationChecks -> Bool
checkFQHN ValidationChecks
checks)

-- | Whether BasicConstraints says the certificate is not a CA.
notCA :: Certificate -> Bool
notCA :: Certificate -> Bool
notCA Certificate
cert = case Extensions -> Maybe (Either [Char] ExtBasicConstraints)
forall a. Extension a => Extensions -> Maybe (Either [Char] a)
extensionGetE (Certificate -> Extensions
certExtensions Certificate
cert) of
    Just (Right (ExtBasicConstraints Bool
False Maybe Integer
_)) -> Bool
True
    Just (Left [Char]
_) -> Bool
True
    Maybe (Either [Char] ExtBasicConstraints)
_ -> Bool
False

isSelfSigned :: Certificate -> Bool
isSelfSigned :: Certificate -> Bool
isSelfSigned Certificate
cert = Certificate -> DistinguishedName
certSubjectDN Certificate
cert DistinguishedName -> DistinguishedName -> Bool
forall a. Eq a => a -> a -> Bool
== Certificate -> DistinguishedName
certIssuerDN Certificate
cert

-- | The maximum number of CA certificates followed from the leaf.
maxChainDepth :: Int
maxChainDepth :: Int
maxChainDepth = Int
20

-- | The maximum number of signatures checked while building paths.
maxSignatureChecks :: Int
maxSignatureChecks :: Int
maxSignatureChecks = Int
100

data NameConstSpec = NameConstSpec
    { NameConstSpec -> Either [Char] [AltName]
ncNames :: Either String [AltName]
    -- ^ names subject to name constraints
    , NameConstSpec -> Either [Char] (Maybe ExtNameConstraints)
ncExt :: Either String (Maybe ExtNameConstraints)
    , NameConstSpec -> Bool
ncSelfIssued :: Bool
    }

-- | The second argument tells whether the CN is used as a host name.
getNameConstSpec :: Certificate -> Bool -> NameConstSpec
getNameConstSpec :: Certificate -> Bool -> NameConstSpec
getNameConstSpec Certificate
cert Bool
useCN =
    NameConstSpec
        { ncNames :: Either [Char] [AltName]
ncNames = Either [Char] [AltName]
names
        , ncExt :: Either [Char] (Maybe ExtNameConstraints)
ncExt = Either [Char] (Maybe ExtNameConstraints)
-> (Either [Char] ExtNameConstraints
    -> Either [Char] (Maybe ExtNameConstraints))
-> Maybe (Either [Char] ExtNameConstraints)
-> Either [Char] (Maybe ExtNameConstraints)
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Maybe ExtNameConstraints
-> Either [Char] (Maybe ExtNameConstraints)
forall a b. b -> Either a b
Right Maybe ExtNameConstraints
forall a. Maybe a
Nothing) ((ExtNameConstraints -> Maybe ExtNameConstraints)
-> Either [Char] ExtNameConstraints
-> Either [Char] (Maybe ExtNameConstraints)
forall a b. (a -> b) -> Either [Char] a -> Either [Char] b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap ExtNameConstraints -> Maybe ExtNameConstraints
forall a. a -> Maybe a
Just) (Maybe (Either [Char] ExtNameConstraints)
 -> Either [Char] (Maybe ExtNameConstraints))
-> Maybe (Either [Char] ExtNameConstraints)
-> Either [Char] (Maybe ExtNameConstraints)
forall a b. (a -> b) -> a -> b
$ Extensions -> Maybe (Either [Char] ExtNameConstraints)
forall a. Extension a => Extensions -> Maybe (Either [Char] a)
extensionGetE Extensions
exts
        , ncSelfIssued :: Bool
ncSelfIssued = Certificate -> Bool
isSelfSigned Certificate
cert
        }
  where
    exts :: Extensions
exts = Certificate -> Extensions
certExtensions Certificate
cert
    subjDN :: DistinguishedName
subjDN = Certificate -> DistinguishedName
certSubjectDN Certificate
cert
    subj :: [AltName]
subj = [DistinguishedName -> AltName
AltNameDN DistinguishedName
subjDN | Bool -> Bool
not ([([Integer], ASN1CharacterString)] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null (DistinguishedName -> [([Integer], ASN1CharacterString)]
getDistinguishedElements DistinguishedName
subjDN))]
    -- RFC 5280: without SAN, emailAddress in the subject is an rfc822Name
    emails :: [AltName]
emails =
        [ [Char] -> AltName
AltNameRFC822 [Char]
e
        | ([Integer]
oid, ASN1CharacterString
v) <- DistinguishedName -> [([Integer], ASN1CharacterString)]
getDistinguishedElements DistinguishedName
subjDN
        , [Integer]
oid [Integer] -> [Integer] -> Bool
forall a. Eq a => a -> a -> Bool
== [Integer
1, Integer
2, Integer
840, Integer
113549, Integer
1, Integer
9, Integer
1]
        , Just [Char]
e <- [ASN1CharacterString -> Maybe [Char]
safeCharacterToString ASN1CharacterString
v]
        ]
    cn :: [AltName]
cn
        | Bool
useCN = case Certificate -> Either [Char] (Maybe [Char], Maybe [AltName])
getNames Certificate
cert of
            Right (Just [Char]
name, Maybe [AltName]
Nothing) -> [AltName -> (IPAddress -> AltName) -> Maybe IPAddress -> AltName
forall b a. b -> (a -> b) -> Maybe a -> b
maybe ([Char] -> AltName
AltNameDNS [Char]
name) IPAddress -> AltName
ipToAltName ([Char] -> Maybe IPAddress
parseIPAddress [Char]
name)]
            Either [Char] (Maybe [Char], Maybe [AltName])
_ -> []
        | Bool
otherwise = []
    names :: Either [Char] [AltName]
names = case Extensions -> Maybe (Either [Char] ExtSubjectAltName)
forall a. Extension a => Extensions -> Maybe (Either [Char] a)
extensionGetE Extensions
exts of
        Maybe (Either [Char] ExtSubjectAltName)
Nothing -> [AltName] -> Either [Char] [AltName]
forall a b. b -> Either a b
Right ([AltName]
subj [AltName] -> [AltName] -> [AltName]
forall a. [a] -> [a] -> [a]
++ [AltName]
emails [AltName] -> [AltName] -> [AltName]
forall a. [a] -> [a] -> [a]
++ [AltName]
cn)
        Just (Right (ExtSubjectAltName [AltName]
alts)) -> [AltName] -> Either [Char] [AltName]
forall a b. b -> Either a b
Right ([AltName]
subj [AltName] -> [AltName] -> [AltName]
forall a. [a] -> [a] -> [a]
++ [AltName]
alts [AltName] -> [AltName] -> [AltName]
forall a. [a] -> [a] -> [a]
++ [AltName]
cn)
        Just (Left [Char]
e) -> [Char] -> Either [Char] [AltName]
forall a b. a -> Either a b
Left [Char]
e

ipToAltName :: IPAddress -> AltName
ipToAltName :: IPAddress -> AltName
ipToAltName (IPv4Address IPv4
ip) = ByteString -> AltName
AltNameIP (ByteString -> AltName) -> ByteString -> AltName
forall a b. (a -> b) -> a -> b
$ [Word8] -> ByteString
B.pack ([Word8] -> ByteString) -> [Word8] -> ByteString
forall a b. (a -> b) -> a -> b
$ (Int -> Word8) -> [Int] -> [Word8]
forall a b. (a -> b) -> [a] -> [b]
map Int -> Word8
forall a b. (Integral a, Num b) => a -> b
fromIntegral ([Int] -> [Word8]) -> [Int] -> [Word8]
forall a b. (a -> b) -> a -> b
$ IPv4 -> [Int]
fromIPv4 IPv4
ip
ipToAltName (IPv6Address IPv6
ip) = ByteString -> AltName
AltNameIP (ByteString -> AltName) -> ByteString -> AltName
forall a b. (a -> b) -> a -> b
$ [Word8] -> ByteString
B.pack ([Word8] -> ByteString) -> [Word8] -> ByteString
forall a b. (a -> b) -> a -> b
$ (Int -> Word8) -> [Int] -> [Word8]
forall a b. (a -> b) -> [a] -> [b]
map Int -> Word8
forall a b. (Integral a, Num b) => a -> b
fromIntegral ([Int] -> [Word8]) -> [Int] -> [Word8]
forall a b. (a -> b) -> a -> b
$ IPv6 -> [Int]
fromIPv6b IPv6
ip

-- | Validate that the current time is between validity bounds
validateTime :: DateTime -> Certificate -> [FailedReason]
validateTime :: DateTime -> Certificate -> [FailedReason]
validateTime DateTime
currentTime Certificate
cert
    | DateTime
currentTime DateTime -> DateTime -> Bool
forall a. Ord a => a -> a -> Bool
< DateTime
before = [FailedReason
InFuture]
    | DateTime
currentTime DateTime -> DateTime -> Bool
forall a. Ord a => a -> a -> Bool
> DateTime
after = [FailedReason
Expired]
    | Bool
otherwise = []
  where
    (DateTime
before, DateTime
after) = Certificate -> (DateTime, DateTime)
certValidity Certificate
cert

-- | 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 :: Certificate -> Either [Char] (Maybe [Char], Maybe [AltName])
getNames Certificate
cert = case Extensions -> Maybe (Either [Char] ExtSubjectAltName)
forall a. Extension a => Extensions -> Maybe (Either [Char] a)
extensionGetE (Extensions -> Maybe (Either [Char] ExtSubjectAltName))
-> Extensions -> Maybe (Either [Char] ExtSubjectAltName)
forall a b. (a -> b) -> a -> b
$ Certificate -> Extensions
certExtensions Certificate
cert of
    Just (Left [Char]
e) -> [Char] -> Either [Char] (Maybe [Char], Maybe [AltName])
forall a b. a -> Either a b
Left [Char]
e
    Just (Right (ExtSubjectAltName [AltName]
names)) -> (Maybe [Char], Maybe [AltName])
-> Either [Char] (Maybe [Char], Maybe [AltName])
forall a b. b -> Either a b
Right (Maybe [Char]
commonName, [AltName] -> Maybe [AltName]
forall a. a -> Maybe a
Just [AltName]
names)
    Maybe (Either [Char] ExtSubjectAltName)
Nothing -> (Maybe [Char], Maybe [AltName])
-> Either [Char] (Maybe [Char], Maybe [AltName])
forall a b. b -> Either a b
Right (Maybe [Char]
commonName, Maybe [AltName]
forall a. Maybe a
Nothing)
  where
    commonName :: Maybe [Char]
commonName = DnElement -> DistinguishedName -> Maybe ASN1CharacterString
getDnElement DnElement
DnCommonName (Certificate -> DistinguishedName
certSubjectDN Certificate
cert) Maybe ASN1CharacterString
-> (ASN1CharacterString -> Maybe [Char]) -> Maybe [Char]
forall a b. Maybe a -> (a -> Maybe b) -> Maybe b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= ASN1CharacterString -> Maybe [Char]
safeCharacterToString

data IPAddress
    = IPv4Address IPv4
    | IPv6Address IPv6
    deriving (IPAddress -> IPAddress -> Bool
(IPAddress -> IPAddress -> Bool)
-> (IPAddress -> IPAddress -> Bool) -> Eq IPAddress
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: IPAddress -> IPAddress -> Bool
== :: IPAddress -> IPAddress -> Bool
$c/= :: IPAddress -> IPAddress -> Bool
/= :: IPAddress -> IPAddress -> Bool
Eq)

toIPAddress :: ByteString -> Maybe IPAddress
toIPAddress :: ByteString -> Maybe IPAddress
toIPAddress ByteString
s = case ByteString -> [Word8]
unpack ByteString
s of
    [Word8
a, Word8
b, Word8
c, Word8
d] -> IPAddress -> Maybe IPAddress
forall a. a -> Maybe a
Just (IPAddress -> Maybe IPAddress) -> IPAddress -> Maybe IPAddress
forall a b. (a -> b) -> a -> b
$ IPv4 -> IPAddress
IPv4Address (IPv4 -> IPAddress) -> IPv4 -> IPAddress
forall a b. (a -> b) -> a -> b
$ [Int] -> IPv4
toIPv4 ([Int] -> IPv4) -> [Int] -> IPv4
forall a b. (a -> b) -> a -> b
$ (Word8 -> Int) -> [Word8] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap Word8 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral [Word8
a, Word8
b, Word8
c, Word8
d]
    [Word8
a, Word8
b, Word8
c, Word8
d, Word8
e, Word8
f, Word8
g, Word8
h, Word8
i, Word8
j, Word8
k, Word8
l, Word8
m, Word8
n, Word8
o, Word8
p] ->
        IPAddress -> Maybe IPAddress
forall a. a -> Maybe a
Just (IPAddress -> Maybe IPAddress) -> IPAddress -> Maybe IPAddress
forall a b. (a -> b) -> a -> b
$
            IPv6 -> IPAddress
IPv6Address (IPv6 -> IPAddress) -> IPv6 -> IPAddress
forall a b. (a -> b) -> a -> b
$
                [Int] -> IPv6
toIPv6
                    [ Word8 -> Word8 -> Int
fuse Word8
a Word8
b
                    , Word8 -> Word8 -> Int
fuse Word8
c Word8
d
                    , Word8 -> Word8 -> Int
fuse Word8
e Word8
f
                    , Word8 -> Word8 -> Int
fuse Word8
g Word8
h
                    , Word8 -> Word8 -> Int
fuse Word8
i Word8
j
                    , Word8 -> Word8 -> Int
fuse Word8
k Word8
l
                    , Word8 -> Word8 -> Int
fuse Word8
m Word8
n
                    , Word8 -> Word8 -> Int
fuse Word8
o Word8
p
                    ]
    [Word8]
_ -> Maybe IPAddress
forall a. Maybe a
Nothing
  where
    fuse :: Word8 -> Word8 -> Int
    fuse :: Word8 -> Word8 -> Int
fuse Word8
a Word8
b = Int -> Int -> Int
forall a. Bits a => a -> Int -> a
shiftL (Word8 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word8
a) Int
8 Int -> Int -> Int
forall a. Bits a => a -> a -> a
.|. (Word8 -> Int
forall a b. (Integral a, Num b) => a -> b
fromIntegral Word8
b)

parseIPAddress :: HostName -> Maybe IPAddress
parseIPAddress :: [Char] -> Maybe IPAddress
parseIPAddress ([Char] -> Maybe IPv4
forall a. Read a => [Char] -> Maybe a
readMaybe -> Just IPv4
ipV4) = IPAddress -> Maybe IPAddress
forall a. a -> Maybe a
Just (IPAddress -> Maybe IPAddress) -> IPAddress -> Maybe IPAddress
forall a b. (a -> b) -> a -> b
$ IPv4 -> IPAddress
IPv4Address IPv4
ipV4
parseIPAddress ([Char] -> Maybe IPv6
forall a. Read a => [Char] -> Maybe a
readMaybe -> Just IPv6
ipV6) = IPAddress -> Maybe IPAddress
forall a. a -> Maybe a
Just (IPAddress -> Maybe IPAddress) -> IPAddress -> Maybe IPAddress
forall a b. (a -> b) -> a -> b
$ IPv6 -> IPAddress
IPv6Address IPv6
ipV6
parseIPAddress [Char]
_ = Maybe IPAddress
forall a. Maybe a
Nothing

-- | Validate that the fqhn is matched by at least one name in the certificate.
-- 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 :: [Char] -> Certificate -> [FailedReason]
validateCertificateName [Char]
fqhn Certificate
cert = case Certificate -> Either [Char] (Maybe [Char], Maybe [AltName])
getNames Certificate
cert of
    Left [Char]
_ -> [[Char] -> FailedReason
NameMismatch [Char]
fqhn]
    Right (Maybe [Char], Maybe [AltName])
names -> [Char] -> (Maybe [Char], Maybe [AltName]) -> [FailedReason]
validateNames [Char]
fqhn (Maybe [Char], Maybe [AltName])
names

validateNames
    :: HostName -> (Maybe String, Maybe [AltName]) -> [FailedReason]
validateNames :: [Char] -> (Maybe [Char], Maybe [AltName]) -> [FailedReason]
validateNames [Char]
fqhn (Maybe [Char]
commonName, Maybe [AltName]
mAltNames) = case [Char] -> Maybe IPAddress
parseIPAddress [Char]
fqhn of
    Just IPAddress
ip
        | IPAddress
ip IPAddress -> [IPAddress] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [IPAddress
a | AltNameIP ByteString
b <- [AltName]
altNames, Just IPAddress
a <- [ByteString -> Maybe IPAddress
toIPAddress ByteString
b]] -> []
        | Bool
otherwise -> [[Char] -> FailedReason
NameMismatch [Char]
fqhn]
    Maybe IPAddress
Nothing -> case Maybe [AltName]
mAltNames of
        Just [AltName]
_ -> [FailedReason] -> [[FailedReason]] -> [FailedReason]
findMatch [] ([[FailedReason]] -> [FailedReason])
-> [[FailedReason]] -> [FailedReason]
forall a b. (a -> b) -> a -> b
$ [[Char] -> [FailedReason]
matchDomain [Char]
n | AltNameDNS [Char]
n <- [AltName]
altNames]
        Maybe [AltName]
Nothing -> case Maybe [Char]
commonName of
            Maybe [Char]
Nothing -> [FailedReason
NoCommonName]
            Just [Char]
cn -> [FailedReason] -> [[FailedReason]] -> [FailedReason]
findMatch [] ([[FailedReason]] -> [FailedReason])
-> [[FailedReason]] -> [FailedReason]
forall a b. (a -> b) -> a -> b
$ [[Char] -> [FailedReason]
matchDomain [Char]
cn]
  where
    altNames :: [AltName]
altNames = [AltName] -> Maybe [AltName] -> [AltName]
forall a. a -> Maybe a -> a
fromMaybe [] Maybe [AltName]
mAltNames

    findMatch :: [FailedReason] -> [[FailedReason]] -> [FailedReason]
    findMatch :: [FailedReason] -> [[FailedReason]] -> [FailedReason]
findMatch [FailedReason]
_ [] = [[Char] -> FailedReason
NameMismatch [Char]
fqhn]
    findMatch [FailedReason]
_ ([] : [[FailedReason]]
_) = []
    findMatch [FailedReason]
acc ([FailedReason]
_ : [[FailedReason]]
xs) = [FailedReason] -> [[FailedReason]] -> [FailedReason]
findMatch [FailedReason]
acc [[FailedReason]]
xs

    matchDomain :: String -> [FailedReason]
    matchDomain :: [Char] -> [FailedReason]
matchDomain [Char]
name = case [Char] -> [[Char]]
splitDot [Char]
name of
        [[Char]]
l
            | ([Char] -> Bool) -> [[Char]] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any ([Char] -> [Char] -> Bool
forall a. Eq a => a -> a -> Bool
== [Char]
"") [[Char]]
l -> [[Char] -> FailedReason
InvalidName [Char]
name]
            | Int -> [[Char]] -> [[Char]]
forall a. Int -> [a] -> [a]
take Int
1 [[Char]]
l [[Char]] -> [[Char]] -> Bool
forall a. Eq a => a -> a -> Bool
== [[Char]
"*"] -> [[Char]] -> [FailedReason]
wildcardMatch (Int -> [[Char]] -> [[Char]]
forall a. Int -> [a] -> [a]
drop Int
1 [[Char]]
l)
            | [[Char]]
l [[Char]] -> [[Char]] -> Bool
forall a. Eq a => a -> a -> Bool
== [Char] -> [[Char]]
splitDot [Char]
fqhn -> [] -- success: we got a match
            | Bool
otherwise -> [[Char] -> FailedReason
NameMismatch [Char]
fqhn]

    -- A wildcard matches a single domain name component.
    --
    -- e.g. *.server.com will match www.server.com but not www.m.server.com
    --
    -- Only 1 wildcard is valid and only for the left-most component. If
    -- used at other positions or if multiples are present
    -- they won't have a wildcard meaning but will be match as normal star
    -- character to the fqhn and inevitably will fail.
    --
    -- e.g. *.*.server.com will try to litteraly match the '*' subdomain of server.com
    --
    -- Also '*' and a wildcard for a single label such as '*.com' are not
    -- accepted as valid wildcards
    wildcardMatch :: [[Char]] -> [FailedReason]
wildcardMatch [[Char]]
l
        | [[Char]] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [[Char]]
l Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
2 = [FailedReason
InvalidWildcard]
        | [[Char]]
l [[Char]] -> [[Char]] -> Bool
forall a. Eq a => a -> a -> Bool
== Int -> [[Char]] -> [[Char]]
forall a. Int -> [a] -> [a]
drop Int
1 ([Char] -> [[Char]]
splitDot [Char]
fqhn) = [] -- success: we got a match
        | Bool
otherwise = [[Char] -> FailedReason
NameMismatch [Char]
fqhn]

    splitDot :: String -> [String]
    splitDot :: [Char] -> [[Char]]
splitDot [] = [[Char]
""]
    splitDot [Char]
x =
        let ([Char]
y, [Char]
z) = (Char -> Bool) -> [Char] -> ([Char], [Char])
forall a. (a -> Bool) -> [a] -> ([a], [a])
break (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'.') [Char]
x
         in (Char -> Char) -> ShowS
forall a b. (a -> b) -> [a] -> [b]
map Char -> Char
toLower [Char]
y [Char] -> [[Char]] -> [[Char]]
forall a. a -> [a] -> [a]
: (if [Char]
z [Char] -> [Char] -> Bool
forall a. Eq a => a -> a -> Bool
== [Char]
"" then [] else [Char] -> [[Char]]
splitDot ([Char] -> [[Char]]) -> [Char] -> [[Char]]
forall a b. (a -> b) -> a -> b
$ Int -> ShowS
forall a. Int -> [a] -> [a]
drop Int
1 [Char]
z)

-- | 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 :: DistinguishedName -> Certificate -> Bool
matchSI DistinguishedName
issuerDN Certificate
issuer =
    DistinguishedName -> DistinguishedName
canonicalDistinguishedName (Certificate -> DistinguishedName
certSubjectDN Certificate
issuer)
        DistinguishedName -> DistinguishedName -> Bool
forall a. Eq a => a -> a -> Bool
== DistinguishedName -> DistinguishedName
canonicalDistinguishedName DistinguishedName
issuerDN

exhaustive :: Bool -> [FailedReason] -> [FailedReason] -> [FailedReason]
exhaustive :: Bool -> [FailedReason] -> [FailedReason] -> [FailedReason]
exhaustive Bool
isExhaustive [FailedReason]
l1 [FailedReason]
l2
    | [FailedReason] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [FailedReason]
l1 = [FailedReason]
l2
    | Bool
isExhaustive = [FailedReason]
l1 [FailedReason] -> [FailedReason] -> [FailedReason]
forall a. [a] -> [a] -> [a]
++ [FailedReason]
l2
    | Bool
otherwise = [FailedReason]
l1

exhaustiveList :: Bool -> [(Bool, [FailedReason])] -> [FailedReason]
exhaustiveList :: Bool -> [(Bool, [FailedReason])] -> [FailedReason]
exhaustiveList Bool
_ [] = []
exhaustiveList Bool
isExhaustive ((Bool
performCheck, [FailedReason]
c) : [(Bool, [FailedReason])]
cs)
    | Bool
performCheck = Bool -> [FailedReason] -> [FailedReason] -> [FailedReason]
exhaustive Bool
isExhaustive [FailedReason]
c (Bool -> [(Bool, [FailedReason])] -> [FailedReason]
exhaustiveList Bool
isExhaustive [(Bool, [FailedReason])]
cs)
    | Bool
otherwise = Bool -> [(Bool, [FailedReason])] -> [FailedReason]
exhaustiveList Bool
isExhaustive [(Bool, [FailedReason])]
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 :: [NameConstSpec] -> [FailedReason]
checkNameConstraints [] = []
checkNameConstraints (NameConstSpec
anchor : [NameConstSpec]
specs0) =
    ([FailedReason] -> [FailedReason])
-> (NameConstState -> [FailedReason])
-> Either [FailedReason] NameConstState
-> [FailedReason]
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either [FailedReason] -> [FailedReason]
forall a. a -> a
id (\NameConstState
st -> NameConstState -> [NameConstSpec] -> [FailedReason]
loop NameConstState
st [NameConstSpec]
specs0) (Either [FailedReason] NameConstState -> [FailedReason])
-> Either [FailedReason] NameConstState -> [FailedReason]
forall a b. (a -> b) -> a -> b
$ NameConstState
-> NameConstSpec -> Either [FailedReason] NameConstState
addNameConst ([[GeneralSubtree]] -> [GeneralSubtree] -> NameConstState
NameConstState [] []) NameConstSpec
anchor
  where
    loop :: NameConstState -> [NameConstSpec] -> [FailedReason]
loop NameConstState
_ [] = []
    loop NameConstState
st (NameConstSpec
spec : [NameConstSpec]
specs) =
        [FailedReason]
check [FailedReason] -> [FailedReason] -> [FailedReason]
forall a. [a] -> [a] -> [a]
++ case [NameConstSpec]
specs of
            [] -> []
            [NameConstSpec]
_ -> ([FailedReason] -> [FailedReason])
-> (NameConstState -> [FailedReason])
-> Either [FailedReason] NameConstState
-> [FailedReason]
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either [FailedReason] -> [FailedReason]
forall a. a -> a
id (\NameConstState
st' -> NameConstState -> [NameConstSpec] -> [FailedReason]
loop NameConstState
st' [NameConstSpec]
specs) (Either [FailedReason] NameConstState -> [FailedReason])
-> Either [FailedReason] NameConstState -> [FailedReason]
forall a b. (a -> b) -> a -> b
$ NameConstState
-> NameConstSpec -> Either [FailedReason] NameConstState
addNameConst NameConstState
st NameConstSpec
spec
      where
        -- self-issued intermediates are exempt but the leaf is not
        check :: [FailedReason]
check
            | NameConstSpec -> Bool
ncSelfIssued NameConstSpec
spec Bool -> Bool -> Bool
&& Bool -> Bool
not ([NameConstSpec] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [NameConstSpec]
specs) = []
            | Bool
otherwise = NameConstState -> Either [Char] [AltName] -> [FailedReason]
validateNames' NameConstState
st (NameConstSpec -> Either [Char] [AltName]
ncNames NameConstSpec
spec)

addNameConst
    :: NameConstState -> NameConstSpec -> Either [FailedReason] NameConstState
addNameConst :: NameConstState
-> NameConstSpec -> Either [FailedReason] NameConstState
addNameConst st :: NameConstState
st@(NameConstState [[GeneralSubtree]]
permitted [GeneralSubtree]
excluded) NameConstSpec
spec = case NameConstSpec -> Either [Char] (Maybe ExtNameConstraints)
ncExt NameConstSpec
spec of
    Left [Char]
e -> [FailedReason] -> Either [FailedReason] NameConstState
forall a b. a -> Either a b
Left [[Char] -> FailedReason
InvalidName ([Char] -> FailedReason) -> [Char] -> FailedReason
forall a b. (a -> b) -> a -> b
$ [Char]
"NameConstraints: " [Char] -> ShowS
forall a. [a] -> [a] -> [a]
++ [Char]
e]
    Right Maybe ExtNameConstraints
Nothing -> NameConstState -> Either [FailedReason] NameConstState
forall a b. b -> Either a b
Right NameConstState
st
    Right (Just (ExtNameConstraints [GeneralSubtree]
p [GeneralSubtree]
e)) ->
        NameConstState -> Either [FailedReason] NameConstState
forall a b. b -> Either a b
Right (NameConstState -> Either [FailedReason] NameConstState)
-> NameConstState -> Either [FailedReason] NameConstState
forall a b. (a -> b) -> a -> b
$ [[GeneralSubtree]] -> [GeneralSubtree] -> NameConstState
NameConstState ([[GeneralSubtree]
p | Bool -> Bool
not ([GeneralSubtree] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [GeneralSubtree]
p)] [[GeneralSubtree]] -> [[GeneralSubtree]] -> [[GeneralSubtree]]
forall a. [a] -> [a] -> [a]
++ [[GeneralSubtree]]
permitted) ([GeneralSubtree]
e [GeneralSubtree] -> [GeneralSubtree] -> [GeneralSubtree]
forall a. [a] -> [a] -> [a]
++ [GeneralSubtree]
excluded)

validateNames' :: NameConstState -> Either String [AltName] -> [FailedReason]
validateNames' :: NameConstState -> Either [Char] [AltName] -> [FailedReason]
validateNames' (NameConstState [] []) Either [Char] [AltName]
_ = []
validateNames' NameConstState
_ (Left [Char]
e) = [[Char] -> FailedReason
InvalidName ([Char] -> FailedReason) -> [Char] -> FailedReason
forall a b. (a -> b) -> a -> b
$ [Char]
"SubjectAltName: " [Char] -> ShowS
forall a. [a] -> [a] -> [a]
++ [Char]
e]
validateNames' (NameConstState [[GeneralSubtree]]
permitted [GeneralSubtree]
excluded) (Right [AltName]
altNames) =
    (AltName -> [FailedReason]) -> [AltName] -> [FailedReason]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap AltName -> [FailedReason]
inc [AltName]
altNames [FailedReason] -> [FailedReason] -> [FailedReason]
forall a. [a] -> [a] -> [a]
++ (AltName -> [FailedReason]) -> [AltName] -> [FailedReason]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap AltName -> [FailedReason]
exc [AltName]
altNames
  where
    inc :: AltName -> [FailedReason]
inc AltName
a
        | ([GeneralSubtree] -> Bool) -> [[GeneralSubtree]] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all (AltName -> [GeneralSubtree] -> Bool
nsMatch AltName
a) [[GeneralSubtree]]
permitted = []
        | Bool
otherwise = [[Char] -> FailedReason
InvalidName ([Char] -> FailedReason) -> [Char] -> FailedReason
forall a b. (a -> b) -> a -> b
$ AltName -> [Char]
forall a. Show a => a -> [Char]
show AltName
a]
    exc :: AltName -> [FailedReason]
exc AltName
a
        | AltName -> [GeneralSubtree] -> Bool
nsNotMatch AltName
a [GeneralSubtree]
excluded = []
        | Bool
otherwise = [[Char] -> FailedReason
InvalidName ([Char] -> FailedReason) -> [Char] -> FailedReason
forall a b. (a -> b) -> a -> b
$ AltName -> [Char]
forall a. Show a => a -> [Char]
show AltName
a]

data NameMatch = NotApplicable | Matched | NotMatched | Unsupported
    deriving (NameMatch -> NameMatch -> Bool
(NameMatch -> NameMatch -> Bool)
-> (NameMatch -> NameMatch -> Bool) -> Eq NameMatch
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: NameMatch -> NameMatch -> Bool
== :: NameMatch -> NameMatch -> Bool
$c/= :: NameMatch -> NameMatch -> Bool
/= :: NameMatch -> NameMatch -> Bool
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 :: AltName -> [GeneralSubtree] -> Bool
nsMatch AltName
a [GeneralSubtree]
gs = (NameMatch -> Bool) -> [NameMatch] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any (NameMatch -> NameMatch -> Bool
forall a. Eq a => a -> a -> Bool
== NameMatch
Matched) [NameMatch]
rs Bool -> Bool -> Bool
|| (NameMatch -> Bool) -> [NameMatch] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all (NameMatch -> NameMatch -> Bool
forall a. Eq a => a -> a -> Bool
== NameMatch
NotApplicable) [NameMatch]
rs
  where
    rs :: [NameMatch]
rs = (GeneralSubtree -> NameMatch) -> [GeneralSubtree] -> [NameMatch]
forall a b. (a -> b) -> [a] -> [b]
map (Bool -> AltName -> GeneralSubtree -> NameMatch
matchSubtree Bool
False AltName
a) [GeneralSubtree]
gs

nsNotMatch :: AltName -> [GeneralSubtree] -> Bool
nsNotMatch :: AltName -> [GeneralSubtree] -> Bool
nsNotMatch AltName
a = (GeneralSubtree -> Bool) -> [GeneralSubtree] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
all ((NameMatch -> [NameMatch] -> Bool
forall a. Eq a => a -> [a] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`elem` [NameMatch
NotApplicable, NameMatch
NotMatched]) (NameMatch -> Bool)
-> (GeneralSubtree -> NameMatch) -> GeneralSubtree -> Bool
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Bool -> AltName -> GeneralSubtree -> NameMatch
matchSubtree Bool
True AltName
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 :: Bool -> AltName -> GeneralSubtree -> NameMatch
matchSubtree Bool
isExcluded AltName
name (GeneralSubtree AltName
base Integer
_ Maybe Integer
_) = case (AltName
name, AltName
base) of
    (AltNameDNS [Char]
n, AltNameDNS [Char]
c) ->
        Bool -> NameMatch
toMatch (Bool -> NameMatch) -> Bool -> NameMatch
forall a b. (a -> b) -> a -> b
$ [Char] -> [Char] -> Bool
dnsInSubtree [Char]
n [Char]
c Bool -> Bool -> Bool
|| (Bool
isExcluded Bool -> Bool -> Bool
&& [Char] -> [Char] -> Bool
wildcardCovers [Char]
n [Char]
c)
    (AltNameDN DistinguishedName
n, AltNameDN DistinguishedName
c) -> Bool -> NameMatch
toMatch (Bool -> NameMatch) -> Bool -> NameMatch
forall a b. (a -> b) -> a -> b
$ DistinguishedName -> DistinguishedName -> Bool
dnInSubtree DistinguishedName
n DistinguishedName
c
    (AltNameIP ByteString
n, AltNameIP ByteString
c) -> ByteString -> ByteString -> NameMatch
ipInSubtree ByteString
n ByteString
c
    (AltNameRFC822 [Char]
n, AltNameRFC822 [Char]
c) -> NameMatch -> (Bool -> NameMatch) -> Maybe Bool -> NameMatch
forall b a. b -> (a -> b) -> Maybe a -> b
maybe NameMatch
Unsupported Bool -> NameMatch
toMatch (Maybe Bool -> NameMatch) -> Maybe Bool -> NameMatch
forall a b. (a -> b) -> a -> b
$ [Char] -> [Char] -> Maybe Bool
emailInSubtree [Char]
n [Char]
c
    (AltNameURI [Char]
n, AltNameURI [Char]
c) -> NameMatch -> ([Char] -> NameMatch) -> Maybe [Char] -> NameMatch
forall b a. b -> (a -> b) -> Maybe a -> b
maybe NameMatch
Unsupported (Bool -> NameMatch
toMatch (Bool -> NameMatch) -> ([Char] -> Bool) -> [Char] -> NameMatch
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ([Char] -> [Char] -> Bool
`hostInSubtree` [Char]
c)) (Maybe [Char] -> NameMatch) -> Maybe [Char] -> NameMatch
forall a b. (a -> b) -> a -> b
$ [Char] -> Maybe [Char]
uriHost [Char]
n
    (AltNameXMPP [Char]
_, AltNameXMPP [Char]
_) -> NameMatch
Unsupported
    (AltNameDNSSRV [Char]
_, AltNameDNSSRV [Char]
_) -> NameMatch
Unsupported
    (AltName, AltName)
_ -> NameMatch
NotApplicable
  where
    toMatch :: Bool -> NameMatch
toMatch Bool
b = if Bool
b then NameMatch
Matched else NameMatch
NotMatched

-- | "example.com" covers itself and its subdomains, ".example.com" only
-- its subdomains.  Compared case-insensitively.
dnsInSubtree :: String -> String -> Bool
dnsInSubtree :: [Char] -> [Char] -> Bool
dnsInSubtree [Char]
n [Char]
c
    | [Char] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Char]
c' = Bool
True
    | [Char]
"." [Char] -> [Char] -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isPrefixOf` [Char]
c' = [Char]
c' [Char] -> [Char] -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isSuffixOf` [Char]
n'
    | Bool
otherwise = [Char]
n' [Char] -> [Char] -> Bool
forall a. Eq a => a -> a -> Bool
== [Char]
c' Bool -> Bool -> Bool
|| (Char
'.' Char -> ShowS
forall a. a -> [a] -> [a]
: [Char]
c') [Char] -> [Char] -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isSuffixOf` [Char]
n'
  where
    n' :: [Char]
n' = (Char -> Char) -> ShowS
forall a b. (a -> b) -> [a] -> [b]
map Char -> Char
toLower [Char]
n
    c' :: [Char]
c' = (Char -> Char) -> ShowS
forall a b. (a -> b) -> [a] -> [b]
map Char -> Char
toLower [Char]
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 :: [Char] -> [Char] -> Bool
wildcardCovers [Char]
n [Char]
c = case [Char] -> [Char] -> Maybe [Char]
forall a. Eq a => [a] -> [a] -> Maybe [a]
stripPrefix [Char]
"*." ((Char -> Char) -> ShowS
forall a b. (a -> b) -> [a] -> [b]
map Char -> Char
toLower [Char]
n) of
    Just [Char]
rest ->
        let c' :: [Char]
c' = (Char -> Char) -> ShowS
forall a b. (a -> b) -> [a] -> [b]
map Char -> Char
toLower [Char]
c
            label :: [Char]
label = Int -> ShowS
forall a. Int -> [a] -> [a]
take ([Char] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Char]
c' Int -> Int -> Int
forall a. Num a => a -> a -> a
- [Char] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Char]
rest Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1) [Char]
c'
         in Bool -> Bool
not ([Char] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Char]
label)
                Bool -> Bool -> Bool
&& Char
'.' Char -> [Char] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`notElem` [Char]
label
                Bool -> Bool -> Bool
&& (Char
'.' Char -> ShowS
forall a. a -> [a] -> [a]
: [Char]
rest) [Char] -> [Char] -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isSuffixOf` [Char]
c'
    Maybe [Char]
Nothing -> Bool
False

hostInSubtree :: String -> String -> Bool
hostInSubtree :: [Char] -> [Char] -> Bool
hostInSubtree [Char]
h [Char]
c
    | [Char]
"." [Char] -> [Char] -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isPrefixOf` [Char]
c' = [Char]
c' [Char] -> [Char] -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isSuffixOf` [Char]
h'
    | Bool
otherwise = [Char]
h' [Char] -> [Char] -> Bool
forall a. Eq a => a -> a -> Bool
== [Char]
c'
  where
    h' :: [Char]
h' = (Char -> Char) -> ShowS
forall a b. (a -> b) -> [a] -> [b]
map Char -> Char
toLower [Char]
h
    c' :: [Char]
c' = (Char -> Char) -> ShowS
forall a b. (a -> b) -> [a] -> [b]
map Char -> Char
toLower [Char]
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 :: [Char] -> [Char] -> Maybe Bool
emailInSubtree [Char]
n [Char]
c = case [Char] -> Maybe ([Char], [Char])
breakAt [Char]
n of
    Just ([Char]
local, [Char]
host) -> Bool -> Maybe Bool
forall a. a -> Maybe a
Just (Bool -> Maybe Bool) -> Bool -> Maybe Bool
forall a b. (a -> b) -> a -> b
$ case [Char] -> Maybe ([Char], [Char])
breakAt [Char]
c of
        Just ([Char]
cLocal, [Char]
cHost) -> [Char]
local [Char] -> [Char] -> Bool
forall a. Eq a => a -> a -> Bool
== [Char]
cLocal Bool -> Bool -> Bool
&& (Char -> Char) -> ShowS
forall a b. (a -> b) -> [a] -> [b]
map Char -> Char
toLower [Char]
host [Char] -> [Char] -> Bool
forall a. Eq a => a -> a -> Bool
== (Char -> Char) -> ShowS
forall a b. (a -> b) -> [a] -> [b]
map Char -> Char
toLower [Char]
cHost
        Maybe ([Char], [Char])
Nothing -> [Char] -> [Char] -> Bool
hostInSubtree [Char]
host [Char]
c
    Maybe ([Char], [Char])
Nothing -> Maybe Bool
forall a. Maybe a
Nothing
  where
    breakAt :: [Char] -> Maybe ([Char], [Char])
breakAt [Char]
x = case (Char -> Bool) -> [Char] -> ([Char], [Char])
forall a. (a -> Bool) -> [a] -> ([a], [a])
break (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
'@') (ShowS
forall a. [a] -> [a]
reverse [Char]
x) of
        ([Char]
rhost, Char
'@' : [Char]
rlocal) -> ([Char], [Char]) -> Maybe ([Char], [Char])
forall a. a -> Maybe a
Just (ShowS
forall a. [a] -> [a]
reverse [Char]
rlocal, ShowS
forall a. [a] -> [a]
reverse [Char]
rhost)
        ([Char], [Char])
_ -> Maybe ([Char], [Char])
forall a. Maybe a
Nothing

-- | The host of a URI with an authority; 'Nothing' for IP literals.
uriHost :: String -> Maybe String
uriHost :: [Char] -> Maybe [Char]
uriHost [Char]
uri = case (Char -> Bool) -> [Char] -> ([Char], [Char])
forall a. (a -> Bool) -> [a] -> ([a], [a])
break (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
== Char
':') [Char]
uri of
    ([Char]
_, Char
':' : Char
'/' : Char
'/' : [Char]
rest) ->
        let authority :: [Char]
authority = (Char -> Bool) -> ShowS
forall a. (a -> Bool) -> [a] -> [a]
takeWhile (Char -> [Char] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`notElem` ([Char]
"/?#" :: String)) [Char]
rest
            hostport :: [Char]
hostport = ShowS
forall a. [a] -> [a]
reverse ShowS -> ShowS
forall a b. (a -> b) -> a -> b
$ (Char -> Bool) -> ShowS
forall a. (a -> Bool) -> [a] -> [a]
takeWhile (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
'@') ShowS -> ShowS
forall a b. (a -> b) -> a -> b
$ ShowS
forall a. [a] -> [a]
reverse [Char]
authority
            host :: [Char]
host = (Char -> Bool) -> ShowS
forall a. (a -> Bool) -> [a] -> [a]
takeWhile (Char -> Char -> Bool
forall a. Eq a => a -> a -> Bool
/= Char
':') [Char]
hostport
         in if [Char] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Char]
host Bool -> Bool -> Bool
|| [Char]
"[" [Char] -> [Char] -> Bool
forall a. Eq a => [a] -> [a] -> Bool
`isPrefixOf` [Char]
hostport Bool -> Bool -> Bool
|| Maybe IPAddress -> Bool
forall a. Maybe a -> Bool
isJust ([Char] -> Maybe IPAddress
parseIPAddress [Char]
host)
                then Maybe [Char]
forall a. Maybe a
Nothing
                else [Char] -> Maybe [Char]
forall a. a -> Maybe a
Just [Char]
host
    ([Char], [Char])
_ -> Maybe [Char]
forall a. Maybe a
Nothing

-- | The subtree is a prefix of the name.  Attribute values are compared
-- case-insensitively with whitespace folded.
dnInSubtree :: DistinguishedName -> DistinguishedName -> Bool
dnInSubtree :: DistinguishedName -> DistinguishedName -> Bool
dnInSubtree (DistinguishedName [([Integer], ASN1CharacterString)]
n) (DistinguishedName [([Integer], ASN1CharacterString)]
c) =
    [([Integer], ASN1CharacterString)] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [([Integer], ASN1CharacterString)]
c Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= [([Integer], ASN1CharacterString)] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [([Integer], ASN1CharacterString)]
n Bool -> Bool -> Bool
&& [Bool] -> Bool
forall (t :: * -> *). Foldable t => t Bool -> Bool
and ((([Integer], ASN1CharacterString)
 -> ([Integer], ASN1CharacterString) -> Bool)
-> [([Integer], ASN1CharacterString)]
-> [([Integer], ASN1CharacterString)]
-> [Bool]
forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith ([Integer], ASN1CharacterString)
-> ([Integer], ASN1CharacterString) -> Bool
forall {a}.
Eq a =>
(a, ASN1CharacterString) -> (a, ASN1CharacterString) -> Bool
eq [([Integer], ASN1CharacterString)]
n [([Integer], ASN1CharacterString)]
c)
  where
    eq :: (a, ASN1CharacterString) -> (a, ASN1CharacterString) -> Bool
eq (a
o1, ASN1CharacterString
v1) (a
o2, ASN1CharacterString
v2) = a
o1 a -> a -> Bool
forall a. Eq a => a -> a -> Bool
== a
o2 Bool -> Bool -> Bool
&& ASN1CharacterString -> Either ASN1CharacterString [Char]
norm ASN1CharacterString
v1 Either ASN1CharacterString [Char]
-> Either ASN1CharacterString [Char] -> Bool
forall a. Eq a => a -> a -> Bool
== ASN1CharacterString -> Either ASN1CharacterString [Char]
norm ASN1CharacterString
v2
    norm :: ASN1CharacterString -> Either ASN1CharacterString [Char]
norm ASN1CharacterString
v = case ASN1CharacterString -> Maybe [Char]
safeCharacterToString ASN1CharacterString
v of
        Just [Char]
str -> [Char] -> Either ASN1CharacterString [Char]
forall a b. b -> Either a b
Right ([Char] -> Either ASN1CharacterString [Char])
-> [Char] -> Either ASN1CharacterString [Char]
forall a b. (a -> b) -> a -> b
$ [[Char]] -> [Char]
unwords ([[Char]] -> [Char]) -> [[Char]] -> [Char]
forall a b. (a -> b) -> a -> b
$ [Char] -> [[Char]]
words ([Char] -> [[Char]]) -> [Char] -> [[Char]]
forall a b. (a -> b) -> a -> b
$ (Char -> Char) -> ShowS
forall a b. (a -> b) -> [a] -> [b]
map Char -> Char
toLower [Char]
str
        Maybe [Char]
Nothing -> ASN1CharacterString -> Either ASN1CharacterString [Char]
forall a b. a -> Either a b
Left ASN1CharacterString
v

-- | An IPv4 or IPv6 address against an address with a mask.
ipInSubtree :: ByteString -> ByteString -> NameMatch
ipInSubtree :: ByteString -> ByteString -> NameMatch
ipInSubtree ByteString
n ByteString
c
    | ByteString -> Int
B.length ByteString
c Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= Int
8 Bool -> Bool -> Bool
&& ByteString -> Int
B.length ByteString
c Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= Int
32 = NameMatch
Unsupported
    | ByteString -> Int
B.length ByteString
n Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= Int
4 Bool -> Bool -> Bool
&& ByteString -> Int
B.length ByteString
n Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= Int
16 = NameMatch
Unsupported
    | Int
2 Int -> Int -> Int
forall a. Num a => a -> a -> a
* ByteString -> Int
B.length ByteString
n Int -> Int -> Bool
forall a. Eq a => a -> a -> Bool
/= ByteString -> Int
B.length ByteString
c = NameMatch
NotMatched
    | Bool
otherwise =
        if [Bool] -> Bool
forall (t :: * -> *). Foldable t => t Bool -> Bool
and
            ( (Word8 -> Word8 -> Word8 -> Bool)
-> [Word8] -> [Word8] -> [Word8] -> [Bool]
forall a b c d. (a -> b -> c -> d) -> [a] -> [b] -> [c] -> [d]
zipWith3
                (\Word8
x Word8
a Word8
m -> Word8
x Word8 -> Word8 -> Word8
forall a. Bits a => a -> a -> a
.&. Word8
m Word8 -> Word8 -> Bool
forall a. Eq a => a -> a -> Bool
== Word8
a Word8 -> Word8 -> Word8
forall a. Bits a => a -> a -> a
.&. Word8
m)
                (ByteString -> [Word8]
B.unpack ByteString
n)
                (ByteString -> [Word8]
B.unpack ByteString
addr)
                (ByteString -> [Word8]
B.unpack ByteString
mask)
            )
            then NameMatch
Matched
            else NameMatch
NotMatched
  where
    (ByteString
addr, ByteString
mask) = Int -> ByteString -> (ByteString, ByteString)
B.splitAt (ByteString -> Int
B.length ByteString
n) ByteString
c

doCriticalExtensionSweep :: Certificate -> [FailedReason]
doCriticalExtensionSweep :: Certificate -> [FailedReason]
doCriticalExtensionSweep Certificate
cert = case Maybe [ExtensionRaw]
mexts of
    Maybe [ExtensionRaw]
Nothing -> []
    Just [ExtensionRaw]
exts ->
        [ [Integer] -> FailedReason
UnknownCriticalExtension [Integer]
oid
        | ExtensionRaw [Integer]
oid Bool
critical ByteString
_ <- [ExtensionRaw]
exts
        , Bool
critical
        , [Integer]
oid [Integer] -> [[Integer]] -> Bool
forall (t :: * -> *) a. (Foldable t, Eq a) => a -> t a -> Bool
`notElem` [[Integer]]
recognizedOIDs
        ]
  where
    Extensions Maybe [ExtensionRaw]
mexts = Certificate -> Extensions
certExtensions Certificate
cert