packages feed

crypton-x509-1.11.1 / Data / X509 / PublicKey.hs

{-# LANGUAGE TypeApplications #-}-- |-- Module      : Data.X509.PublicKey-- License     : BSD-style-- Maintainer  : Vincent Hanquez <vincent@snarc.org>-- Stability   : experimental-- Portability : unknown---- Public key handling in X.509 infrastructuremodule Data.X509.PublicKey (    PubKey (..),    PubKeyEC (..),    PubKeyDH,    dhPublicKey,    pubkeyDH_p,    pubkeyDH_g,    pubkeyDH_q,    pubkeyDH_j,    pubkeyDH_validation,    pubkeyDH_y,    SerializedPoint (..),    pubkeyToAlg,) whereimport Data.ASN1.BinaryEncodingimport Data.ASN1.BitArrayimport Data.ASN1.Encodingimport Data.ASN1.Typesimport Data.Bitsimport Data.ByteArray (convert)import Data.ByteString (ByteString)import Data.X509.AlgorithmIdentifierimport Data.X509.Internalimport Data.X509.OIDimport Crypto.Error (CryptoFailable (..))import Crypto.Number.Basic (numBytes)import Crypto.Number.Serialize (i2osp, i2ospOf_, os2ip)import qualified Crypto.PubKey.Curve25519 as X25519import qualified Crypto.PubKey.Curve448 as X448import qualified Crypto.PubKey.DSA as DSAimport qualified Crypto.PubKey.ECC.Types as ECCimport qualified Crypto.PubKey.Ed25519 as Ed25519import qualified Crypto.PubKey.Ed448 as Ed448import qualified Crypto.PubKey.MLDSA as MLDSAimport qualified Crypto.PubKey.MLKEM as MLKEMimport qualified Crypto.PubKey.RSA.Types as RSAimport Data.Wordimport qualified Data.ByteString as B-- | Serialized Elliptic Curve Pointnewtype SerializedPoint = SerializedPoint ByteString    deriving (Show, Eq)-- | Elliptic Curve Public Key---- TODO: missing support for binary curve.data PubKeyEC    = PubKeyEC_Prime        { pubkeyEC_pub :: SerializedPoint        , pubkeyEC_a :: Integer        , pubkeyEC_b :: Integer        , pubkeyEC_prime :: Integer        , pubkeyEC_generator :: SerializedPoint        , pubkeyEC_order :: Integer        , pubkeyEC_cofactor :: Integer        , pubkeyEC_seed :: Integer        }    | PubKeyEC_Named        { pubkeyEC_name :: ECC.CurveName        , pubkeyEC_pub :: SerializedPoint        }    deriving (Show, Eq)-- | X9.42 Diffie-Hellman public key (RFC 3279 2.3.3).  The constructor is-- hidden; use 'dhPublicKey' and record update syntax.data PubKeyDH = PubKeyDH_    { pubkeyDH_p :: Integer    -- ^ the prime    , pubkeyDH_g :: Integer    -- ^ the generator    , pubkeyDH_q :: Integer    -- ^ the prime factor of p-1    , pubkeyDH_j :: Maybe Integer    -- ^ the subgroup factor    , pubkeyDH_validation :: Maybe (BitArray, Integer)    -- ^ seed and pgenCounter    , pubkeyDH_y :: Integer    -- ^ the public value    }    deriving (Show, Eq)-- | A DH public key from p, g, q and the public value, without j and-- validation parameters.dhPublicKey :: Integer -> Integer -> Integer -> Integer -> PubKeyDHdhPublicKey p g q y = PubKeyDH_ p g q Nothing Nothing y-- | Public key types known and used in X.509data PubKey    = -- | RSA public key      PubKeyRSA RSA.PublicKey    | -- | RSASSA-PSS public key, restricted to the parameters if any      PubKeyRSAPSS RSA.PublicKey (Maybe PSSParams)    | -- | DSA public key      PubKeyDSA DSA.PublicKey    | -- | X9.42 DH public key      PubKeyDH PubKeyDH    | -- | EC public key      PubKeyEC PubKeyEC    | -- | X25519 public key      PubKeyX25519 X25519.PublicKey    | -- | X448 public key      PubKeyX448 X448.PublicKey    | -- | Ed25519 public key      PubKeyEd25519 Ed25519.PublicKey    | -- | Ed448 public key      PubKeyEd448 Ed448.PublicKey    | -- | ML-DSA-44 public key      PubKeyMLDSA44 (MLDSA.VerificationKey MLDSA.MLDSA44)    | -- | ML-DSA-65 public key      PubKeyMLDSA65 (MLDSA.VerificationKey MLDSA.MLDSA65)    | -- | ML-DSA-87 public key      PubKeyMLDSA87 (MLDSA.VerificationKey MLDSA.MLDSA87)    | -- | ML-KEM-512 public key      PubKeyMLKEM512 (MLKEM.EncapsulationKey MLKEM.MLKEM512)    | -- | ML-KEM-768 public key      PubKeyMLKEM768 (MLKEM.EncapsulationKey MLKEM.MLKEM768)    | -- | ML-KEM-1024 public key      PubKeyMLKEM1024 (MLKEM.EncapsulationKey MLKEM.MLKEM1024)    | -- | unrecognized format      PubKeyUnknown OID B.ByteString    deriving (Show, Eq)-- Public key are in the format:---- Start Sequence--      OID (Public key algorithm)--      [public key specific format]--      BitString-- End Sequenceinstance ASN1Object PubKey where    fromASN1 (Start Sequence : Start Sequence : OID pkalg : xs)        | pkalg == getObjectID PubKeyALG_RSA =            case removeNull xs of                End Sequence : BitString bits : End Sequence : xs2 -> decodeASN1Err "RSA" bits xs2 (toPubKeyRSA . rsaPubFromASN1)                _ -> Left ("fromASN1: X509.PubKey: unknown RSA format: " ++ show xs)        | pkalg == getObjectID PubKeyALG_RSAPSS = do            (mp, ys) <- pssKeyParamsFromASN1 xs            case ys of                BitString bits : End Sequence : xs2 ->                    decodeASN1Err "RSA-PSS" bits xs2 (toPubKeyRSAPSS mp . rsaPubFromASN1)                _ -> Left ("fromASN1: X509.PubKey: unknown RSA-PSS format: " ++ show xs)        | pkalg == getObjectID PubKeyALG_DSA =            case xs of                Start Sequence : IntVal p : IntVal q : IntVal g : End Sequence : End Sequence                    : BitString bits                    : End Sequence                    : xs2 ->                        decodeASN1Err                            "DSA"                            bits                            xs2                            ( \l -> case l of                                [IntVal dsapub] ->                                    let pubkey =                                            DSA.PublicKey                                                { DSA.public_params =                                                    DSA.Params                                                        { DSA.params_p = p                                                        , DSA.params_q = q                                                        , DSA.params_g = g                                                        }                                                , DSA.public_y = dsapub                                                }                                     in Right (PubKeyDSA pubkey, [])                                _ -> Left "fromASN1: X509.PubKey: unknown DSA format"                            )                _ -> Left "fromASN1: X509.PubKey: unknown DSA format"        | pkalg == getObjectID PubKeyALG_DH =            case xs of                Start Sequence : IntVal p : IntVal g : IntVal q : rest ->                    let (j, rest1) = case rest of                            IntVal j' : r -> (Just j', r)                            r -> (Nothing, r)                        (v, rest2) = case rest1 of                            Start Sequence : BitString seed : IntVal c : End Sequence : r ->                                (Just (seed, c), r)                            r -> (Nothing, r)                     in case rest2 of                            End Sequence : End Sequence : BitString bits : End Sequence : xs2 ->                                decodeASN1Err "DH" bits xs2 $ \l -> case l of                                    [IntVal y] -> Right (PubKeyDH (PubKeyDH_ p g q j v y), [])                                    _ -> Left "fromASN1: X509.PubKey: unknown DH format"                            _ -> Left "fromASN1: X509.PubKey: unknown DH format"                _ -> Left "fromASN1: X509.PubKey: unknown DH format"        | pkalg == getObjectID PubKeyALG_EC =            case xs of                OID curveOid : End Sequence : BitString bits : End Sequence : xs2 ->                    case lookupByOID curvesOIDTable curveOid of                        Just curveName -> Right (PubKeyEC $ PubKeyEC_Named curveName (bitArrayToPoint bits), xs2)                        Nothing -> Left ("fromASN1: X509.Pubkey: EC unknown curve " ++ show curveOid)                Start Sequence                    : IntVal 1                    : Start Sequence                    : OID [1, 2, 840, 10045, 1, 1]                    : IntVal prime                    : End Sequence                    : Start Sequence                    : OctetString a                    : OctetString b                    : BitString seed                    : End Sequence                    : OctetString generator                    : IntVal order                    : IntVal cofactor                    : End Sequence                    : End Sequence                    : BitString pub                    : End Sequence                    : xs2 ->                        Right                            ( PubKeyEC $                                PubKeyEC_Prime                                    { pubkeyEC_pub = bitArrayToPoint pub                                    , pubkeyEC_a = os2ip a                                    , pubkeyEC_b = os2ip b                                    , pubkeyEC_prime = prime                                    , pubkeyEC_generator = SerializedPoint generator                                    , pubkeyEC_order = order                                    , pubkeyEC_cofactor = cofactor                                    , pubkeyEC_seed = os2ip $ bitArrayGetData seed                                    }                            , xs2                            )                _ ->                    Left $ "fromASN1: X509.PubKey: unknown EC format: " ++ show xs        | pkalg == getObjectID PubKeyALG_X25519 =            case xs of                End Sequence : BitString bits : End Sequence : xs2 -> decodeCF "X25519" PubKeyX25519 bits xs2 X25519.publicKey                _ -> Left ("fromASN1: X509.PubKey: unknown X25519 format: " ++ show xs)        | pkalg == getObjectID PubKeyALG_X448 =            case xs of                End Sequence : BitString bits : End Sequence : xs2 -> decodeCF "X448" PubKeyX448 bits xs2 X448.publicKey                _ -> Left ("fromASN1: X509.PubKey: unknown X448 format: " ++ show xs)        | pkalg == getObjectID PubKeyALG_Ed25519 =            case xs of                End Sequence : BitString bits : End Sequence : xs2 -> decodeCF "Ed25519" PubKeyEd25519 bits xs2 Ed25519.publicKey                _ -> Left ("fromASN1: X509.PubKey: unknown Ed25519 format: " ++ show xs)        | pkalg == getObjectID PubKeyALG_Ed448 =            case xs of                End Sequence : BitString bits : End Sequence : xs2 -> decodeCF "Ed448" PubKeyEd448 bits xs2 Ed448.publicKey                _ -> Left ("fromASN1: X509.PubKey: unknown Ed448 format: " ++ show xs)        -- RFC 9881 Section 4: the parameters are absent and the BIT STRING        -- is the raw public key.        | pkalg == getObjectID PubKeyALG_MLDSA44 =            case xs of                End Sequence : BitString bits : End Sequence : xs2 -> decodeCF "ML-DSA-44" PubKeyMLDSA44 bits xs2 MLDSA.verificationKey                _ -> Left ("fromASN1: X509.PubKey: unknown ML-DSA-44 format: " ++ show xs)        | pkalg == getObjectID PubKeyALG_MLDSA65 =            case xs of                End Sequence : BitString bits : End Sequence : xs2 -> decodeCF "ML-DSA-65" PubKeyMLDSA65 bits xs2 MLDSA.verificationKey                _ -> Left ("fromASN1: X509.PubKey: unknown ML-DSA-65 format: " ++ show xs)        | pkalg == getObjectID PubKeyALG_MLDSA87 =            case xs of                End Sequence : BitString bits : End Sequence : xs2 -> decodeCF "ML-DSA-87" PubKeyMLDSA87 bits xs2 MLDSA.verificationKey                _ -> Left ("fromASN1: X509.PubKey: unknown ML-DSA-87 format: " ++ show xs)        | pkalg == getObjectID PubKeyALG_MLKEM512 =            case xs of                End Sequence : BitString bits : End Sequence : xs2 ->                    decodeCF "ML-KEM-512" PubKeyMLKEM512 bits xs2 (MLKEM.encapsulationKey @MLKEM.MLKEM512)                _ -> Left ("fromASN1: X509.PubKey: unknown ML-KEM-512 format: " ++ show xs)        | pkalg == getObjectID PubKeyALG_MLKEM768 =            case xs of                End Sequence : BitString bits : End Sequence : xs2 ->                    decodeCF "ML-KEM-768" PubKeyMLKEM768 bits xs2 (MLKEM.encapsulationKey @MLKEM.MLKEM768)                _ -> Left ("fromASN1: X509.PubKey: unknown ML-KEM-768 format: " ++ show xs)        | pkalg == getObjectID PubKeyALG_MLKEM1024 =            case xs of                End Sequence : BitString bits : End Sequence : xs2 ->                    decodeCF "ML-KEM-1024" PubKeyMLKEM1024 bits xs2 (MLKEM.encapsulationKey @MLKEM.MLKEM1024)                _ -> Left ("fromASN1: X509.PubKey: unknown ML-KEM-1024 format: " ++ show xs)        -- parameters of unknown algorithms are not kept        | otherwise = case dropParams (0 :: Int) xs of            BitString bits : End Sequence : xs2 ->                Right (PubKeyUnknown pkalg (bitArrayGetData bits), xs2)            _ -> Left ("fromASN1: X509.PubKey: unknown format for " ++ show pkalg)      where        dropParams 0 (End Sequence : r) = r        dropParams n (Start _ : r) = dropParams (n + 1) r        dropParams n (End _ : r) = dropParams (n - 1) r        dropParams n (_ : r) = dropParams n r        dropParams _ [] = []        decodeASN1Err format bits xs2 f =            case safeDecode (decodeASN1' BER (bitArrayGetData bits)) of                Left err ->                    Left                        ("fromASN1: X509.PubKey " ++ format ++ " bitarray cannot be parsed: " ++ err)                Right s -> case f s of                    Left err -> Left err                    Right (r, []) -> Right (r, xs2)                    -- anything after the key must not leak into the outer stream                    Right _ ->                        Left ("fromASN1: X509.PubKey " ++ format ++ " bitarray has trailing data")        toPubKeyRSA = either Left (\(rsaKey, r) -> Right (PubKeyRSA rsaKey, r))        toPubKeyRSAPSS mp = either Left (\(rsaKey, r) -> Right (PubKeyRSAPSS rsaKey mp, r))        bitArrayToPoint = SerializedPoint . bitArrayGetData        removeNull (Null : r) = r        removeNull l = l        decodeCF format c bits xs2 f = case f (bitArrayGetData bits) of            CryptoPassed pk -> Right (c pk, xs2)            CryptoFailed err ->                Left                    ( "fromASN1: X509.PubKey "                        ++ format                        ++ " bitarray contains an invalid public key: "                        ++ show err                    )    fromASN1 l = Left ("fromASN1: X509.PubKey: unknown format:" ++ show l)    toASN1 a = \xs -> encodePK a ++ xs-- | Convert a Public key to the Public Key Algorithm typepubkeyToAlg :: PubKey -> PubKeyALGpubkeyToAlg (PubKeyRSA _) = PubKeyALG_RSApubkeyToAlg (PubKeyRSAPSS _ _) = PubKeyALG_RSAPSSpubkeyToAlg (PubKeyDSA _) = PubKeyALG_DSApubkeyToAlg (PubKeyDH _) = PubKeyALG_DHpubkeyToAlg (PubKeyEC _) = PubKeyALG_ECpubkeyToAlg (PubKeyX25519 _) = PubKeyALG_X25519pubkeyToAlg (PubKeyX448 _) = PubKeyALG_X448pubkeyToAlg (PubKeyEd25519 _) = PubKeyALG_Ed25519pubkeyToAlg (PubKeyEd448 _) = PubKeyALG_Ed448pubkeyToAlg (PubKeyMLDSA44 _) = PubKeyALG_MLDSA44pubkeyToAlg (PubKeyMLDSA65 _) = PubKeyALG_MLDSA65pubkeyToAlg (PubKeyMLDSA87 _) = PubKeyALG_MLDSA87pubkeyToAlg (PubKeyMLKEM512 _) = PubKeyALG_MLKEM512pubkeyToAlg (PubKeyMLKEM768 _) = PubKeyALG_MLKEM768pubkeyToAlg (PubKeyMLKEM1024 _) = PubKeyALG_MLKEM1024pubkeyToAlg (PubKeyUnknown oid _) = PubKeyALG_Unknown oidencodePK :: PubKey -> [ASN1]encodePK key = asn1Container Sequence (encodeInner key)  where    pkalg = OID $ getObjectID $ pubkeyToAlg key    encodeInner (PubKeyRSA pubkey) =        asn1Container Sequence [pkalg, Null] ++ [BitString $ toBitArray bits 0]      where        bits = encodeASN1' DER $ rsaPubToASN1 pubkey []    encodeInner (PubKeyRSAPSS pubkey mp) =        pssKeyAlgToASN1 mp [BitString $ toBitArray bits 0]      where        bits = encodeASN1' DER $ rsaPubToASN1 pubkey []    encodeInner (PubKeyDSA pubkey) =        asn1Container Sequence ([pkalg] ++ dsaseq) ++ [BitString $ toBitArray bits 0]      where        dsaseq =            asn1Container                Sequence                [ IntVal (DSA.params_p params)                , IntVal (DSA.params_q params)                , IntVal (DSA.params_g params)                ]        params = DSA.public_params pubkey        bits = encodeASN1' DER [IntVal $ DSA.public_y pubkey]    encodeInner (PubKeyEC (PubKeyEC_Named curveName (SerializedPoint bits))) =        asn1Container Sequence [pkalg, OID eOid] ++ [BitString $ toBitArray bits 0]      where        eOid = case lookupOID curvesOIDTable curveName of            Just oid -> oid            _ -> error ("undefined curve OID: " ++ show curveName)    encodeInner (PubKeyEC k@PubKeyEC_Prime{}) =        asn1Container Sequence ([pkalg] ++ params) ++ [BitString $ toBitArray pub 0]      where        SerializedPoint pub = pubkeyEC_pub k        SerializedPoint gen = pubkeyEC_generator k        size = numBytes (pubkeyEC_prime k)        params =            asn1Container Sequence $                [IntVal 1]                    ++ asn1Container                        Sequence                        [OID [1, 2, 840, 10045, 1, 1], IntVal (pubkeyEC_prime k)]                    ++ asn1Container                        Sequence                        [ OctetString (i2ospOf_ size (pubkeyEC_a k))                        , OctetString (i2ospOf_ size (pubkeyEC_b k))                        , BitString $ toBitArray (i2osp (pubkeyEC_seed k)) 0                        ]                    ++ [ OctetString gen                       , IntVal (pubkeyEC_order k)                       , IntVal (pubkeyEC_cofactor k)                       ]    encodeInner (PubKeyX25519 pubkey) =        asn1Container Sequence [pkalg] ++ [BitString $ toBitArray (convert pubkey) 0]    encodeInner (PubKeyX448 pubkey) =        asn1Container Sequence [pkalg] ++ [BitString $ toBitArray (convert pubkey) 0]    encodeInner (PubKeyEd25519 pubkey) =        asn1Container Sequence [pkalg] ++ [BitString $ toBitArray (convert pubkey) 0]    encodeInner (PubKeyEd448 pubkey) =        asn1Container Sequence [pkalg] ++ [BitString $ toBitArray (convert pubkey) 0]    encodeInner (PubKeyMLDSA44 pubkey) =        asn1Container Sequence [pkalg] ++ [BitString $ toBitArray (convert pubkey) 0]    encodeInner (PubKeyMLDSA65 pubkey) =        asn1Container Sequence [pkalg] ++ [BitString $ toBitArray (convert pubkey) 0]    encodeInner (PubKeyMLDSA87 pubkey) =        asn1Container Sequence [pkalg] ++ [BitString $ toBitArray (convert pubkey) 0]    encodeInner (PubKeyMLKEM512 pubkey) =        asn1Container Sequence [pkalg] ++ [BitString $ toBitArray (convert pubkey) 0]    encodeInner (PubKeyMLKEM768 pubkey) =        asn1Container Sequence [pkalg] ++ [BitString $ toBitArray (convert pubkey) 0]    encodeInner (PubKeyMLKEM1024 pubkey) =        asn1Container Sequence [pkalg] ++ [BitString $ toBitArray (convert pubkey) 0]    encodeInner (PubKeyDH k) =        asn1Container Sequence ([pkalg] ++ params) ++ [BitString $ toBitArray bits 0]      where        params =            asn1Container Sequence $                [IntVal (pubkeyDH_p k), IntVal (pubkeyDH_g k), IntVal (pubkeyDH_q k)]                    ++ maybe [] (\j -> [IntVal j]) (pubkeyDH_j k)                    ++ maybe                        []                        (\(seed, c) -> asn1Container Sequence [BitString seed, IntVal c])                        (pubkeyDH_validation k)        bits = encodeASN1' DER [IntVal $ pubkeyDH_y k]    encodeInner (PubKeyUnknown _ l) =        asn1Container Sequence [pkalg, Null] ++ [BitString $ toBitArray l 0]rsaPubToASN1 :: RSA.PublicKey -> [ASN1] -> [ASN1]rsaPubToASN1 pubkey xs =    Start Sequence        : IntVal (RSA.public_n pubkey)        : IntVal (RSA.public_e pubkey)        : End Sequence        : xsrsaPubFromASN1 :: [ASN1] -> Either String (RSA.PublicKey, [ASN1])rsaPubFromASN1 (Start Sequence : IntVal smodulus : IntVal pubexp : End Sequence : xs) =    Right (pub, xs)  where    pub =        RSA.PublicKey            { RSA.public_size = numBytes modulus            , RSA.public_n = modulus            , RSA.public_e = pubexp            }    -- some bad implementation will not serialize ASN.1 integer properly, leading    -- to negative modulus. if that's the case, we correct it.    modulus = toPositive smodulusrsaPubFromASN1    ( Start Sequence            : IntVal ver            : Start Sequence            : OID oid            : Null            : End Sequence            : OctetString bs            : xs        )        | ver /= 0 = Left "rsaPubFromASN1: Invalid version, expecting 0"        | oid /= [1, 2, 840, 113549, 1, 1, 1] =            Left "rsaPubFromASN1: invalid OID"        | otherwise =            let inner = either strError rsaPubFromASN1 $ safeDecode $ decodeASN1' BER bs                strError = Left . ("fromASN1: RSA.PublicKey: " ++)             in case inner of                    Right (k, []) -> Right (k, xs)                    Right _ -> Left "fromASN1: RSA.PublicKey: trailing data"                    Left e -> Left ersaPubFromASN1 _ =    Left "fromASN1: RSA.PublicKey: unexpected format"-- some bad implementation will not serialize ASN.1 integer properly, leading-- to negative modulus.toPositive :: Integer -> IntegertoPositive int    | int < 0 = uintOfBytes $ bytesOfInt int    | otherwise = int  where    uintOfBytes = foldl (\acc n -> (acc `shiftL` 8) + fromIntegral n) 0    bytesOfInt :: Integer -> [Word8]    bytesOfInt n = case nints of        h : _ | testBit h 7 -> nints        _ -> 0xff : nints      where        nints = reverse $ plusOne $ reverse $ map complement $ bytesOfUInt (abs n)        plusOne [] = [1]        plusOne (x : xs) = if x == 0xff then 0 : plusOne xs else (x + 1) : xs    bytesOfUInt x = reverse (list x)      where        list i =            if i <= 0xff                then [fromIntegral i]                else (fromIntegral i .&. 0xff) : list (i `shiftR` 8)