-- |-- Module : Data.X509.Signed-- License : BSD-style-- Maintainer : Vincent Hanquez <vincent@snarc.org>-- Stability : experimental-- Portability : unknown---- Exposes helpers for X509 certificate and revocation list, signed structures.---- Signed structures are of the form:-- Sequence {-- object a-- signatureAlgorithm AlgorithmIdentifier-- signatureValue BitString-- }---- Unfortunately as lots of signed objects published have been signed on an-- arbitrary BER ASN1 encoding (instead of using the unique DER encoding) or in-- a non-valid DER implementation, we need to keep the raw data being signed,-- as we can't recompute the bytestring used to sign for non compliant cases.---- Signed represent the pure data type for compliant cases, and SignedExact-- the real world situation of having to deal with compliant and non-compliant cases.module Data.X509.Signed ( -- * Types Signed (..), SignedExact, -- * SignedExact to Signed getSigned, getSignedData, -- * Marshalling function encodeSignedObject, decodeSignedObject, -- * Object to Signed and SignedExact objectToSignedExact, objectToSignedExactF, objectToSigned, signedToExact,) whereimport Control.Arrow (first)import Control.Monad (guard)import Data.ASN1.BinaryEncodingimport Data.ASN1.BitArrayimport Data.ASN1.Encodingimport Data.ASN1.Typesimport Data.Bits (shiftL, (.&.), (.|.))import Data.ByteString (ByteString)import qualified Data.ByteString as Bimport Data.X509.AlgorithmIdentifierimport Data.X509.Internal (safeDecode)-- | Represent a signed object using a traditional X509 structure.---- When dealing with external certificate, use the SignedExact structure-- not this one.data (Show a, Eq a, ASN1Object a) => Signed a = Signed { signedObject :: a -- ^ Object to sign , signedAlg :: SignatureALG -- ^ Signature Algorithm used , signedSignature :: B.ByteString -- ^ Signature as bytes } deriving (Show, Eq)-- | Represent the signed object plus the raw data that we need to-- keep around for non compliant case to be able to verify signature.data (Show a, Eq a, ASN1Object a) => SignedExact a = SignedExact { getSigned :: Signed a -- ^ get the decoded Signed data , exactObjectRaw :: B.ByteString -- ^ The raw representation of the object a -- TODO: in later version, replace with offset in exactRaw , encodeSignedObject :: B.ByteString -- ^ The raw representation of the whole signed structure } deriving (Show, Eq)-- | Get the signed data for the signaturegetSignedData :: (Show a, Eq a, ASN1Object a) => SignedExact a -> B.ByteStringgetSignedData = exactObjectRaw-- | make a 'SignedExact' copy of a 'Signed' object---- As the signature is already generated, expect the-- encoded object to have been made on a compliant DER ASN1 implementation.---- It's better to use 'objectToSignedExact' instead of this.signedToExact :: (Show a, Eq a, ASN1Object a) => Signed a -> SignedExact asignedToExact signed = sExact where (sExact, ()) = objectToSignedExact fakeSigFunction (signedObject signed) fakeSigFunction _ = (signedSignature signed, signedAlg signed, ())-- | Transform an object into a 'SignedExact' objectobjectToSignedExact :: (Show a, Eq a, ASN1Object a) => (ByteString -> (ByteString, SignatureALG, r)) -- ^ signature function -> a -- ^ object to sign -> (SignedExact a, r)objectToSignedExact signatureFunction object = (signedExact, val) where (val, signedExact) = objectToSignedExactF (wrap . signatureFunction) object wrap (b, s, r) = (r, (b, s))-- | A generalization of 'objectToSignedExact' where the signature function-- runs in an arbitrary functor. This allows for example to sign using an-- algorithm needing random values.objectToSignedExactF :: (Functor f, Show a, Eq a, ASN1Object a) => (ByteString -> f (ByteString, SignatureALG)) -- ^ signature function -> a -- ^ object to sign -> f (SignedExact a)objectToSignedExactF signatureFunction object = fmap buildSignedExact (signatureFunction objRaw) where buildSignedExact (sigBits, sigAlg) = let signed = Signed { signedObject = object , signedAlg = sigAlg , signedSignature = sigBits } signedRaw = encodeASN1' DER signedASN1 signedASN1 = Start Sequence : objASN1 ( toASN1 sigAlg ( BitString (toBitArray sigBits 0) : End Sequence : [] ) ) in SignedExact signed objRaw signedRaw objASN1 = \xs -> Start Sequence : toASN1 object (End Sequence : xs) objRaw = encodeASN1' DER (objASN1 [])-- | Transform an object into a 'Signed' object.---- It's recommended to use the SignedExact object instead of Signed.objectToSigned :: (Show a, Eq a, ASN1Object a) => ( ByteString -> (ByteString, SignatureALG, r) ) -> a -> (Signed a, r)objectToSigned signatureFunction object = first getSigned $ objectToSignedExact signatureFunction object-- | Try to parse a bytestring that use the typical X509 signed structure formatdecodeSignedObject :: (Show a, Eq a, ASN1Object a) => ByteString -> Either String (SignedExact a)decodeSignedObject b = either Left parseSigned $ safeDecode $ decodeASN1' BER b where parseSigned l = case l of -- The common case, a SEQUENCE of a SEQUENCE and two more values, -- read without copying the outer SEQUENCE: the decoder's values are -- balanced, every Start having a matching End of the same type, so -- an End where a value is expected is the outer SEQUENCE's. Start Sequence : xs | null (dropValues 1 xs) , Start Sequence : ys <- xs -> let (sigAlgSeq, rem2) = splitIn (dropValues 1 ys) (sigSeq, rem3) = splitIn rem2 in parts (fromASN1 (contents ys)) sigAlgSeq sigSeq (case rem3 of [End _] -> True; _ -> False) _ -> case splitValue l of (outer, []) -> onSequence outer $ \l2 -> let (objSeq, rem1) = splitValue l2 (sigAlgSeq, rem2) = splitValue rem1 (sigSeq, rem3) = splitValue rem2 in parts (onSequence objSeq fromASN1) sigAlgSeq sigSeq (null rem3) _ -> Left "signed object error: trailing data" parts obj sigAlgSeq sigSeq noTrailing = case (obj, sigSeq) of _ | not noTrailing -> Left "signed object error: trailing data" (Right (o, []), [BitString signature]) -> case fromASN1 sigAlgSeq of Left err -> Left ("signed object error sigalg: " ++ err) Right (sigAlg, []) -> let signed = Signed { signedObject = o , signedAlg = sigAlg , signedSignature = bitArrayGetData signature } in case signedBytes b of Just rawObj -> Right $ SignedExact { getSigned = signed , exactObjectRaw = rawObj , encodeSignedObject = b } Nothing -> Left "signed object error: invalid encoding" Right _ -> Left "signed object error sigalg: trailing data" (Right (_, []), _) -> Left "signed object error: invalid signature" (Right (_, remObj), _) -> Left $ ("signed object error: remaining stream in object: " ++ show remObj) (Left err, _) -> Left $ ("signed object error: " ++ err) onSequence (Start Sequence : l) f = case reverse l of (End Sequence : l2) -> f $ reverse l2 _ -> Left "signed object error: invalid sequence" onSequence _ _ = Left "signed object error: expecting a sequence"-- | The first value of a list, with all its contents if it starts a-- construction, and the rest of the list.splitValue :: [ASN1] -> ([ASN1], [ASN1])splitValue [] = ([], [])splitValue (x@(Start _) : xs) = (x : takeValues 1 xs, dropValues 1 xs)splitValue (x : xs) = ([x], xs)-- | As 'splitValue', for a list that ends with the 'End' of the-- construction it is in: that 'End' is not a value.splitIn :: [ASN1] -> ([ASN1], [ASN1])splitIn xs@(End _ : _) = ([], xs)splitIn xs = splitValue xs-- | The values up to and including the 'End' that closes @i@ open-- constructions.takeValues :: Int -> [ASN1] -> [ASN1]takeValues 0 _ = []takeValues _ [] = []takeValues i (y : ys) = y : takeValues (depth i y) ys-- | The values before the 'End' that closes the construction they are in.contents :: [ASN1] -> [ASN1]contents = go (0 :: Int) where go _ [] = [] go 0 (End _ : _) = [] go i (y : ys) = y : go (depth i y) ys-- | The values after the 'End' that closes @i@ open constructions.dropValues :: Int -> [ASN1] -> [ASN1]dropValues 0 ys = ysdropValues _ [] = []dropValues i (y : ys) = dropValues (depth i y) ysdepth :: Int -> ASN1 -> Intdepth i (Start _) = i + 1depth i (End _) = i - 1depth i _ = i-- | The bytes of the signed object, as received: the header and contents of-- the first value inside the outer construction of an encoding that-- 'decodeASN1'' accepted with BER.---- The signed object is read as the decoder reads it. Everything else is-- not covered by the signature, so it must be in DER: the outer SEQUENCE-- covering the whole input, the signature algorithm, and the signature-- BIT STRING with no unused bits.signedBytes :: ByteString -> Maybe ByteStringsignedBytes b = do (0x30, start, outerEnd) <- derHeader 0 guard (outerEnd == B.length b) end <- valueEnd start guard (end >= start && end <= outerEnd) algEnd <- derValue end (0x03, sigStart, sigEnd) <- derHeader algEnd guard (sigEnd == outerEnd && sigStart < sigEnd && B.index b sigStart == 0) Just (B.take (end - start) (B.drop start b)) where -- A DER header at i: identifier octet, start and end of contents. derHeader i = do w <- byte i guard (w .&. 0x1f /= 0x1f) (n, j) <- derLength (i + 1) guard (n <= B.length b - j) Just (w, j, j + n) -- A definite length in its shortest form, at most 4 octets. derLength i = do l <- byte i if l < 0x80 then Just (fromIntegral l, i + 1) else do let k = fromIntegral (l .&. 0x7f) guard (k >= 1 && k <= 4 && k <= B.length b - (i + 1)) let ls = B.take k (B.drop (i + 1) b) n = B.foldl' (\a x -> (a `shiftL` 8) .|. fromIntegral x) 0 ls guard (if k == 1 then n >= 0x80 else B.head ls /= 0) Just (n, i + 1 + k) -- The end of a DER value at i. derValue i = do (w, j, e) <- derHeader i if w .&. 0x20 /= 0 then derContents j e else Just e derContents j e | j == e = Just e | otherwise = do k <- derValue j guard (k <= e) derContents k e valueEnd i = do h <- header i let j = hdrEnd h case hdrLength h of Nothing | hdrConstructed h -> contentsEnd j | otherwise -> Nothing Just n | hdrConstructed h -> if n >= 0 then Just (j + n) else Nothing -- A primitive length that does not fit an Int is read as -- empty contents. | n <= 0 -> Just j | otherwise -> Just (j + n) -- The end of indefinite-length contents starting at i: after the -- end-of-contents header that closes them. contentsEnd i | i >= B.length b = Nothing | otherwise = do h <- header i if isEOC h then Just (hdrEnd h) else valueEnd i >>= contentsEnd isEOC h = hdrUniversal h && hdrTag h == 0 header :: Int -> Maybe Header header i = do w <- byte i let universal = w < 0x40 constructed = w .&. 0x20 /= 0 if w .&. 0x1f /= 0x1f then len universal (fromIntegral (w .&. 0x1f)) constructed (i + 1) else do t <- byte (i + 1) if t == 0x80 then Nothing else longTag universal constructed 0 (i + 1) longTag universal constructed acc i = do t <- byte i let acc' = (acc `shiftL` 7) + fromIntegral (t .&. 0x7f) if t .&. 0x80 /= 0 then longTag universal constructed acc' (i + 1) else len universal acc' constructed (i + 1) len universal tag constructed i = do l <- byte i let hdr = Header universal tag constructed case l of _ | l < 0x80 -> Just (hdr (Just (fromIntegral l)) (i + 1)) 0x80 -> Just (hdr Nothing (i + 1)) _ -> do let k = fromIntegral (l .&. 0x7f) if k > B.length b - (i + 1) then Nothing else Just $ hdr ( Just ( B.foldl' (\a x -> (a `shiftL` 8) .|. fromIntegral x) 0 (B.take k (B.drop (i + 1) b)) ) ) (i + 1 + k) byte i | i < B.length b = Just (B.index b i) | otherwise = Nothing-- | A header: universal class, tag, constructed, length ('Nothing' for an-- indefinite length), and the position after it.data Header = Header { hdrUniversal :: !Bool , hdrTag :: !Int , hdrConstructed :: !Bool , hdrLength :: !(Maybe Int) , hdrEnd :: !Int }