packages feed

crypton-x509-validation-1.11.0: Data/X509/Validation/Signature.hs

{-# LANGUAGE RankNTypes #-}

-- |
-- Module      : Data.X509.Validation.Signature
-- License     : BSD-style
-- Maintainer  : Vincent Hanquez <vincent@snarc.org>
-- Stability   : experimental
-- Portability : unknown
--
-- X.509 Certificate and CRL signature verification
module Data.X509.Validation.Signature (
    verifySignedSignature,
    verifySignature,
    SignatureVerification (..),
    SignatureFailure (..),
) where

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

import Data.ASN1.BinaryEncoding
import Data.ASN1.Encoding
import Data.ASN1.Types
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.
--
-- When SignatureFailed is return, the signature shouldn't be
-- accepted.
--
-- Other values are only useful to differentiate the failure
-- reason, but are all equivalent to failure.
data SignatureVerification
    = -- | verification succeeded
      SignaturePass
    | -- | verification failed
      SignatureFailed SignatureFailure
    deriving (Show, Eq)

-- | Various failure possible during signature checking
data SignatureFailure
    = -- | signature doesn't verify
      SignatureInvalid
    | -- | algorithm and public key mismatch, cannot proceed
      SignaturePubkeyMismatch
    | -- | unimplemented signature algorithm
      SignatureUnimplemented
    deriving (Show, Eq)

-- | Verify a Signed object against a specified public key
verifySignedSignature
    :: (Show a, Eq a, ASN1Object a)
    => SignedExact a
    -> PubKey
    -> SignatureVerification
verifySignedSignature signedObj pubKey =
    verifySignature
        (signedAlg signed)
        pubKey
        (getSignedData signedObj)
        (signedSignature signed)
  where
    signed = getSigned signedObj

-- | verify signature using parameter
verifySignature
    :: SignatureALG
    -- ^ Signature algorithm used
    -> PubKey
    -- ^ Public key to use for verify
    -> ByteString
    -- ^ Certificate data that need to be verified
    -> ByteString
    -- ^ Signature to verify
    -> SignatureVerification
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 ->
            if f cdata signature
                then SignaturePass
                else SignatureFailed SignatureInvalid
    | otherwise = SignatureFailed SignaturePubkeyMismatch
  where
    verifyF (PubKeyRSA key) = Just $ rsaVerify hashALG key
    verifyF (PubKeyDSA key)
        | hashALG == HashSHA1 = Just $ dsaVerify SHA1 key
        | hashALG == HashSHA224 = Just $ dsaVerify SHA224 key
        | hashALG == HashSHA256 = Just $ dsaVerify SHA256 key
        | otherwise = Nothing
    verifyF (PubKeyEC key) = verifyECDSA hashALG key
    verifyF _ = Nothing

    dsaToSignature :: ByteString -> Maybe DSA.Signature
    dsaToSignature b =
        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 = 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 =
        case toSig signature of
            CryptoPassed sig
                | verify key cdata sig -> SignaturePass
                | 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' DER sigBS of
            Left _ -> False
            Right [Start Sequence, IntVal r, IntVal s, End Sequence] ->
                let curve = ECC.getCurveByName curveName
                 in case unserializePoint curve pub of
                        Nothing -> False
                        Just p ->
                            let pubkey = ECDSA.PublicKey curve p
                             in (ecdsaVerify hashALG) pubkey (ECDSA.Signature r s) msg
            Right _ -> False

    ecdsaVerify HashMD2 = ECDSA.verify MD2
    ecdsaVerify HashMD5 = ECDSA.verify MD5
    ecdsaVerify HashSHA1 = ECDSA.verify SHA1
    ecdsaVerify HashSHA224 = ECDSA.verify SHA224
    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